I have the following piece of code which is a snippet of the entire thing. Basically I am trying to have a form, with the option of creating multiple entries of the same form on a button click. The aim is to store the data in an array of objects where each object represents one form.
The problem is that, although I am managing to create the second entry in the state that is defined in the parent component, when I try to enter text in the 2nd entry with onChange
, the 1st entry is removed.
My guess is that I am doing something wrong in the logic of how I am trying to save the key events, but I cannot pinpoint it.
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
Ignore the preview part as it is redundant for the problem I am facing.
Child Component
import React from 'react'
import { ReactNode, useState } from 'react'
import { IExperience } from '.'
import { Preview } from './preview'
export const Message = ( { setPreview,data,setData }: {setPreview: any,data: IExperience[],setData: Dispatch<SetStateAction<IExperience[]>>} ) => {
let [count,setCount] = useState(0)
let formRows: ReactNode = []
const formHandler = (i:number) => {
console.log(data) //Console log here also shows 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 is 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>
)
}
Again I am leaving out redundant stuff so that it stays focused on the problem.
I am not able to find a similar question to this, or a solution online
Hope this the code is clear 🙂