How can I store and update multiple values in React useState? if one of the value is in array?

215 Views Asked by At

I have a series of user data elements that I'm collecting inside a React component using single useState Hook.

 const [allValues, setAllValues] = useState<IProduct>({
    title: '',
    name: '',
    category: '',
    price: 0,
    image: '',
    size: [],
    color: [],
    inStock: true,
  });

we can see two of them is array.

 const changeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
    setAllValues({ ...allValues, [e.target.name]: e.target.value });
    console.log(allValues);
  };

and the input box are like these... what are the changes i should make?

 <input
        type='text'
        className='form-control'
        id='name'
        name='name'
        placeholder='Enter a Name'
        onChange={changeHandler}
        />
1

There are 1 best solutions below

0
Koala On
setAllValues({
 ...allValues,
 toUpdate: newValue
});

Is different from

setAllValues(prev => ({
 ...prev, 
  toUpdate: newValue
}));

Hope it helps