2

I am having trouble updating my state object that has an array of objects inside. There are few things that I have tried but none of them worked. Here is an example of my state object. With the example below, I want to update the values for test and test2 depending on whatever the user types in input field. Can someone guide me in the right direction. Thank you!

this.state = {
   someProperty: {
      someOtherProperty: [
          object in array: {
             test: true,
             test2: false
          },
          object in array: {
             test: true
             test2: false
          }
          ..
      ]
      ...
   }
   ...
}

My attempt on updating the value inside the object is as follows:

this.setState(prevState => ({
    ...prevState,
    someProperty: {
        ...prevState.someProperty,
        someOtherProperty: [
            ...prevState.someProperty.someOtherProperty, 
            test: false
        ]
    }
}))
3
  • would you like to update all item in someOtherProperty as test: false Commented Mar 17, 2022 at 16:49
  • No. I would like specific one. For example, if they want to update the first object in someOtherProperty as test: false then the other object shouldn't get updated. I have access to the index but not sure how to incorporate that into the setSate. Commented Mar 17, 2022 at 16:51
  • you cannot put test: false directly, because someOtherProperty is an array of object. Commented Mar 17, 2022 at 16:54

1 Answer 1

2

You can create an array latestSomeOtherProperty, update the wanted index and then;

const latestSomeOtherProperty = someOtherProperty.map(prop=>{...prop, test: false}); // it updates all but you can put condition here

this.setState(prevState => ({
    ...prevState,
    someProperty: {
        ...prevState.someProperty,
        someOtherProperty: [
            ...latestSomeOtherProperty
        ]
    }
}))
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, I think that can work. But is there no direct way to update the property using the spread operator?
It is an array you need to update the correct item, so need to loop it to find and update. Otherwise you will add a new item into the array
Ok great. I just went with that approach. Before setting the state, I am just looping thru that array and updating that specific value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.