Trying to update a property inside state and want to know if I need to do both in order for the change to happen to one of them
I am trying to update the state using setTimeout function. If I have 2 properties in side the this.state object but in the setTimeout function I only update one of those objects then can I use the other property still?
2
Answers
Yes, you can still use the other property that you didn’t update in the
setTimeout
function. Updating one property in the state usingsetState
oruseState
doesn’t affect the other properties in the state.Here’s a simple example to illustrate this:
if you are using the useState hook to manage your state if you set a new object in timeout the other state that you are not providing value for them will be lost because the new object will be replaced with the old one instead you can give the setState( that you get from useState hook ) a function that accepts a argument which is your previous status
note that if you’re using the class component none of this is nessessory and the this.setState method will take care of that if it is your case just provide to the this.setState method an object with the fields that you want to update it will be fine.