Add new content to object

I'm facing some issue trying to stock data inside an array. I've created a component input which I use many times. Each input stock different data about a user. I would like to format an object where all this information will be stock in a json type. For this I use react context. But the thing is that, each time I write data inside my field, the previous one is erased. I know how to get insert inside an array after the previous state, but in the case of an object, ...prevState is not working. Moreover, how can I use the label I pass as props inside the json ? Because I put label in thinking that it would actually take the props value, but it doesn't and it just fill the data with label.

This is the component

type Label = {
    label: string
    type: string

export const Forms = ({ label, type }: Label) => {    
    const {userData, setUserData} = useContext(RegisterContext)

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
     // setUserData(prev => [prev, e.target.value])  this is what I used to do with array
        setUserData({type: e.target.value})

    return (
        <div className="flex flex-col w-64">
            <span className="text-appiness-darkblue">{label}</span>
            <input onChange={handleChange} type={type} className="rounded-md bg-appiness-green focus:outline-none focus:ring focus:border-appiness-darkblue"/>

and this is how I call it

<div className="grid grid-cols-2 justify-items-center w-5/12">
    <Forms type="text" label="Username"/>
    <Forms type="string" label="First name"/>
    <Forms type="string" label="Last name"/>
    <Forms type="string" label="Email"/>
    <Forms type="password" label="Password"/>
    <Forms type="date" label="Date of Birth"/>

Submitted June 20th 2021 by Admin


Try out to spread the state and the type field:

 const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { e.preventDefault() setUserData({...userData, type: e.target.value}) }

Admin | 2 months ago

Relevant Questions