mottosson :
I'm keeping state in a functional component using the useState hook and want to update a single value without having to explicitly set all other attributes, so I thought using the spread operator would work, but it does not!
This is my state:
const [state, setState] = useState({
data: [],
currentIndex: 0,
editMode: false
});
Can someone explain why this doesn't work...
setState({ editMode: value, ...state });
...when this does:
setState({ editMode: value, data: [], currentIndex: 0 });
Whats the difference? Can I use the spread operator or have I misunderstood something?
Here is a CodeSandbox example to demonstrate the issue.
user9408899 :
Just reverse the order:
setState({ ...state, editMode: value });
Otherwise, you are overwriting editMode
's value with the old value.