Sending a Typed useState Hook to a child component results in it being interpreted as undefined, even if the defaultState is not

This code snippet showcases my attempt at creating a form with the functionality to generate multiple entries of the same form upon a button click. The ultimate goal is to store the input data in an array of objects, where each object corresponds to one complete form submission.

Parent Component

export interface IExperience {
    position: string,
    location: string, 
    startDate: string,
    endDate: string,
    description: string
}

const Experience = () => {
    let [preview,setPreview] = useState(false)
    let [data,setData] = useState<IExperience[]>([{position: '', location: '', startDate: '', endDate: '', description: ''}]) // Default state is not undefined
    let [button,setButton] = useState('Edit')

    return (
        <div className={styles.visitorContainer}>
            <Nav />
            {preview ? <Message setPreview={setPreview} data={data} setData={setData} /> : <Preview setPreview={setPreview} data={data} setData={setData} button={button} setButton={setButton}/>}
            <Foot />
        </div>
    )
}
 
export default Experience

The preview section can be ignored as it is irrelevant to the issue at hand.

Child Component

import React from 'react'
import { ReactNode, useState } from 'react'
import { IExperience } from '.'
import { Preview } from './preview'

export const Message = ( { setPreview }: any, { data,setData }: any ) => {
    let [count,setCount] = useState(0)
    let formRows: ReactNode = []

    const formHandler = (i:number) => {
        console.log(data) //The console log indicates that data is undefined

        return formRows = [
             (<div key={`innerDiv${i}`}>
                <div><h2>Entry {i+1}</h2></div>
                <div>
                    <label>Position</label>
                    <input type="text" placeholder='Engineer' onChange={(e) => setData({...data,position: e.target.value})} value={data.position} /> //Error occurs here (data is undefined)
                </div>
            </div>)
         ]
    }

    const updateHandler = () => {
        setCount(prev => prev+1)
    }

    return (
        <div>
            <div>
                <div>
                </div>
                <form onSubmit={(e) => sendData(e)}>
                    {[...Array(count+1)].map((d,i) => (<div key={`outerDiv${i}`} >{formHandler(i)}</div>))}
                    <div>
                        <input type="button" value='+' onClick={() => updateHandler()} />
                    </div>
        
                </form>
            </div>
        </div>
    )
}

I have been exploring this issue for days without finding a solution online, hence turning to posting my own question. Your insights are greatly appreciated!

I hope the code is clear and concise :)

Answer №1

React components usually accept only a single props object, but the Message component in your code snippet is currently taking two arguments.

export const Message = (
  { setPreview }: any,  // argument 1
  { data, setData }: any // argument 2 (undefined!)
) => {

To correct this issue, you should destructure all props from the first argument, which is the props object. Also, I recommend verifying the types as I'm not very familiar with Typescript.

interface I_Message {
  setPreview: React.Dispatch<SetStateAction<boolean>>,
  data: IExperience[],
  setData: React.Dispatch<SetStateAction<IExperience>>
}

export const Message = ({ setPreview, data, setData }: I_Message) => {
  ...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"PHP and Javascript Validation Library: Building Confidence in Your Data

Looking for a PHP form validation library that can work independently outside of any PHP framework? It should be able to handle basic validations like checking for empty fields, using regex, validating email addresses, and alphanumeric characters. Ideally, ...

Guide to adjusting the color of Fluent UI icon when hovering with mouse?

I've been implementing Fluent UI in my current project. When initializing my button, I use this straightforward JavaScript code: iconProps: { iconName: 'NewFolder', styles: { root: { color: 'orang ...

When working with Typescript, it is important to correctly identify elements as checkboxes in order to avoid any red underlines when referencing

When trying to check the input type of an element, such as a checkbox in TypeScript, I encounter the issue of the 'element.checked' property being underlined in red. The code snippet below shows how I attempt to address this: element: HTMLElemen ...

The functionality of ItemSliding appears to be disabled when used in combination with

Could you please help me figure out why the Me button is not visible? I implemented the ItemSliding component. Here is the link to the stackblitz project. The issue is within the home folder. I am trying to create a list like the one below: UI https:// ...

Exploring ways to pass props in functional components in React Native

I am currently exploring how to create an API in React Native with TypeScript without using the class extends component. However, I am struggling to figure out how to access and send props from one const view to another function: App.tsx import React, {us ...

What is the best way to simulate a constructor-created class instance in jest?

Suppose there is a class called Person which creates an instance of another class named Logger. How can we ensure that the method of Logger is being called when an instance of Person is created, as shown in the example below? // Logger.ts export default cl ...

Display Nested Data in Angular Material Table: A Step-by-Step Guide

I recently received a REST API response from the following URL: { "list": [ { "id": 1, "login": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c08190f08234d3c0508521f1311"& ...

Resetting modal form validation with Bootstrap 4

I have attempted various approaches to reset a bootstrap modal form (data and validation) with no luck. There are no issues in ie, but in firefox the fields still show up as red when resetting or reloading the form. It would be greatly appreciated if som ...

The date in a nodejs application appears to be shifted by one day

Despite similar questions being asked before here, the solutions provided did not resolve my issue. Here is the scenario I am dealing with: https://i.sstatic.net/H9rcO.png Upon clicking save, I collect data from certain fields to generate a date using th ...

Having trouble opening a materialize modal in Angular 2?

I am facing an issue where the modal does not open when the component loads, and I cannot figure out why. Any assistance would be greatly appreciated. component.html: <div id="modal" class="modal modal-fixed-footer" materialize="modal" [materializeAct ...

Discover the method for two form fields to submit data to a distant page, located two pages away

Currently, I'm trying to figure out the best approach for having two fields submitted to a page that is located two pages away. To provide more context, let me elaborate on the situation. On the initial page, there will be two fields - workshop title ...

When utilizing the Angular 2 Stack, the Typescript Reflect.getMetadata('design:type'...) method may return an Object instead of a Date

When running the code sample below, it outputs "[Function: Date]", which is as expected. import 'reflect-metadata' function logType(target : any, key : string) { var t = Reflect.getMetadata("design:type", target, key); console.log(`${k ...

Including a Javascript library (jsencrypt) in an Angular 2 application

I have gone through countless tutorials on this particular issue, but unfortunately, I have not yet found a solution. Let me provide some context first. I am working on an Angular 2 application and I need to incorporate this JS library for encryption: http ...

Show array elements in Angular framework

I need help with displaying a list that contains three columns: menu, menuItem, and order. The desired display format is to show menu and menuItem ordered by order as follows: Menu 1 : order 200 Menu 2 : order 230 Menu 3 : order 250 Menu item 1 : order 2 ...

What is the best way to distribute items into an array?

What is the correct way to push objects into an array similar to how the spread operator works for non-objects? I am looking for a solution like this: state.selected = [state.selected, ...action.payload] // Type 'object' is not an array type. I ...

Error: The function visitor.visitUnaryOperatorExpr is not defined as a function

I recently started developing an Angular app with a purchased template and collaborating with another developer. Initially, I was able to successfully build the project for production using ng build --prod. However, when trying to build it again yesterday, ...

Updating CSS class for a label when a radio button is selected in Angular 6

Within my Angular component, I've set up a radio button group like so: <label class="btn-{{cl1}}"> <input type="radio" value="am" name="time" formControlName="time1" (change)="cl1=active" >9:00am </label> I am looking for an effi ...

Utilizing Angular 16 to Link Component Input with Parent Route Parameter

Picture a scenario where there is a component (some.component.ts) in Angular 16 that retrieves the value for its foo property from activeRoute, specifically from the parent route. Take a look at the code snippet below: @Input() foo!: string; constructor(p ...

Why did the developers of Angular 2+ choose to use JavaScript Objects instead of Typescript Classes for defining Router routes?

When working with the Angular 2+ Router, the standard approach involves defining routes in the app-routing module. app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; ...

"Encountering a 'Module Not Found' error in Node.js after

Recently, I added a node-module to my project using the command: npm install typescript --save-dev However, when I tried running: tsc Windows displayed an error message indicating that "tsc" is an unknown command. Strangely, this issue does not occur o ...