0

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>) => {
        e.preventDefault()
     // 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"/>
        </div>
    )
}

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"/>
</div>
samuel potter
  • 189
  • 3
  • 13

1 Answers1

1

Try out to spread the state and the type field:

 const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        e.preventDefault()
        setUserData({...userData, type: e.target.value})
    }
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
  • is there anyway I could dynamically use my `label` passed on props as a key ? Because I tried `label: e.target.value` and it wrote label instead of the password, username etc – samuel potter Jun 20 '21 at 08:02
  • please explain more – Boussadjra Brahim Jun 20 '21 at 08:06
  • as you can see when I call the component, I pass it props, one of them being the label name, example "email", "password" etc, when I fill the userData hooks, I would like to dynamically use this label as a "key" for the json. In the code you wrote, I would like the `type` because the value of the label props – samuel potter Jun 20 '21 at 08:09
  • 1
    you could try something like `setUserData({...userData, [label]: e.target.value})` – Boussadjra Brahim Jun 20 '21 at 08:12