I have a useState in nextjs that has values like this:
const [sampleData, setSampleData] = useState({
value1: ''
value2: ''
value3: []
});
If I want to update the state of value1 for instance while keeping the rest of the state, I would do something like this:
setSampleData({...sampleData, value1: 'new value'});
This works. However, if I want to update the state of value3 which is an array and still keep the previous array contents it has before, how do I achieve this?
Doing something like this would replace the entire state of value3 array with the new set of arrays:
setSampleData({...sampleData, value3: [new array]});
Is it possible or should I simply use another format entirely such as useReducer
hook?
3
Answers
currecntly you have some options to achieve this,
Option1:
Option2:
You can use an inner spread such as:
For adding extra logic to the setter, You can also pass a callback function to the state setter as such (instead of just the new state)
You can refer the docs to read more about it, but I guess this should work for your case.
The returned value of this callback is what gets set as the new state