Home > OS >  Cannot update the state of an object within the state (react)
Cannot update the state of an object within the state (react)

Time:06-26

I have an object variable within the state of my react app. I initialize it with the structure that I want the object to have. Late I am trying to update that object using the setState function. My issue is, I can't get it to actually update anything within the state. The way my code currently looks is:

// the initial state
var initialState = {
  object: {
   foo: '',
   bar: 0,
   array: [<an array of objects>]
 }
};

// in componentDidMount
this.state = initialState;

// updating the object that is within the state (also in componentDidMount)
let object = {
  foo: 'Value',
  bar: 90,
  array: [<a populated array of objects>]
};
this.setState(prevState => ({
  ...prevState.object,
  ...object
}));
console.log(this.state.object); // returns the object defined in initial state

I am really not sure how to fix this issue. I have also been trying a few other methods (especially the ones outlined in this post: Updating an object with setState in React I have not tried every method outlined in that post but the ones I have been trying have not been working and I figure that this means it is a mistake that does not involve which method I am using. Any insight into this issue would be greatly appreciated. I tried to make this code as concise as possible but if you want to see the exact code I am using (which is pretty much just this but more) just ask.

CodePudding user response:

Edit 2

You have to care each object key equality.
You can do this.

this.setState((prevState) => {
  console.log('logging state: ', prevState)

 return {
  ...prevState.object,
  object:{ ...object }
  })
)}

  • Related