Reputation: 77
I'm using React right now and I'm struggling with updating a state object.
I defined a state variable and filled it with an object:
const [connections, setConnections] = useState({...platformConnections})
Now I want to update this state object with setConnections(). But when I try something like this:
setConnections({connectionA: {connected: true}})
it just updates the entire object when I log it.
How can I update this state variable and keep the other values from before the update?
Upvotes: 2
Views: 8314
Reputation: 8158
Calling setConnections
will set an entire new value to connections
, it's your responsibility to make sure you keep the values you are not updating.
For example, if you set a string like this:
setConnections('new value')
Now, connections
will have new value
instead of an object. That being said, in order to keep previous values you will have to either use Object.assign
or the spread operator ...
.
setConnections({
...connections,
connectionA: { ...connections.connectionA, connected: true }
})
That will work in most cases, however there are some edge cases where the value of connections
might be changing frequently and given that setConnections
runs async, you might not be getting the current values and therefore you might lose some data, to prevent this problem you can use a function to get the current state first and then set the values you need.
setConnections(prev => ({
...prev,
connectionA: { ...prev.connectionA, connected: true }
})
)
In this case prev
has the current values on any given time, and you can safely assign whatever you need.
Upvotes: 2
Reputation: 175
What you have done is overwritten the state with just {connectionA: {connected: true}}
Please see https://reactjs.org/docs/hooks-reference.html#functional-updates
For updating state based on prev values along with the help of the spread operator
setConnectitions ( prevConnections => ({
...prevConnections,
connectionA: {...prevConnections.connectionA ,connected : true}
}));
In the above, prevConnections prop uses the previous state and then creates a new obj using spread operator which is the three dots ... and then overwrite the property you want to modify and set the value.
Upvotes: 0