简体   繁体   中英

Updating object with useState

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM