ReactJS - how do I update nested and "normal" state properties?

react update nested state array
react hooks nested state
nested state in react
spread operator update nested object
react setstate array of objects
nested array in react js
react hooks update nested object
react update object in array

This is how my state looks like:

constructor(props, context) {
    super(props, context);

    this.state = {
      show: false,
      btnLabel: 'GO!',
      car: {
        owner: false, 
        manufacturer: false, 
        color: false
      }
    };
  }

and this is how I modify state:

handleClickFetchPrice() {
      this.setState({btnLabel: 'Fetching data...' });
      console.log(this.state.fetchPriceBtn);

      const url = 'some url';
      axios.get(url)
        .then(res => {
          let car = [...this.state.car];
          car.owner = res.data.owner;
          car.manufacturer = res.data.manufacturer;
          car.color = res.data.color;
          this.setState({car});
        })
  }

The attribute car is updated, but fetchPriceBtn is not - the output of console.log(this.state.fetchPriceBtn); is still GO!.

What am I overlooking? Why the fetchPriceBtn is not updated?


React setState is an asynchronous process - you don't know exactly when it will be updated, you can only schedule the update.

To achieve your desired functionality, you can provide a callback into the setState method.

this.setState({ btnLabel: 'Fetching data...' }, () => console.log(this.state.fetchPriceBtn))

You can learn more following the documentation on the method.

Updating react nested state properties - DEV Community ‍ ‍ , React setState doesn't take care of nested properties out of the box, we will take a look at how to fix this. Tagged with react, javascript. Dismiss Join GitHub today. GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.


@christopher is right, setState is an asynchronous process. But when second time call handleClickFetchPrice() function your btnLabel is value will be equal to Fetching data...

Document how to update nested state properties · Issue #1101 , In setState, what should one return from the updater function in order to update a nested property of the state? This isn't documented, and it https://stackoverflow.​com/questions/34071160/how-to-update-object-in-react-js etc. ReactJs is a powerful library allows to use component inside another component, sometime you may need to change state of the parent component from a child component. to do this communication between the child and parent, you can use a function on child component as a Prop, when this function is called will be detected on parent component that allows you change the state of parent from the child component.


As answered in previous answers setState is asynchronous, so your console.log can't catch up the state change immediately. Again as suggested you can use callback function to track this change but if you use console.log just for debugging or want to see what changes in your state you can do this in your render function. And using a callback just for debug is not a nice way. Its purpose somehow different and if you check the official documentation, componentDidMount method is being suggested for such logic.

render() {
    console.log( this.state.foo );
    return (...)
}

If you do that you see two console.log output, one before state change and one after.

Also, your state operations might be enhanced. You car property is not an array, but you are converting it to an array and setting it? Is this what you intend:

axios.get(url)
    .then(res => {
        const { owner, manufacturer, color } = res.data;
        this.setState( prevState => ( { car: { ...prevState.car, owner, manufacturer, color } } ) );
     })

Here we are not mutating our state directly, instead we are using spread operator and setting the desired properties. For your example we are setting the whole property actually.

One last note, I think you want to do that something like that:

this.setState( { btnLabel: "fetching } );
axios.get(url)
    .then(res => {
        const { owner, manufacturer, color } = res.data;
        this.setState( prevState => ( { car: { ...prevState.car, owner, manufacturer, color }, btnLabel: "go" } ) );
     })

If your intention is somehow to do a status change/check this might no be a good logic as you have seen setState is not synchronous. Do this carefully.

Correct way of updating nested value via setState? : reactjs, How does it know what to update? well with it's virtualDom representation of the actual Dom. You can optimaze react's “reconcilation” with shouldComponetUpdate  FYI, I have a work-in-progress set of new pages for the Redux docs on "Structuring Reducers", and the page on Immutable Update Patterns discusses this a bit. Overall, the basic approaches to avoid nested object updates are: flatten your state; compose reducers more; Use utility libraries that abstract out the update steps


Deeply Nested Objects and Redux, In very simple terms, the React rendering process is sensitive only to the immutable updates of the state. This means that any change you make  Instead, React “flushes” the state updates at the end of the browser event. This results in significant performance improvements in larger apps. This is an implementation detail so avoid relying on it directly. In the future versions, React will batch updates by default in more cases.


Immutability Helpers – React, update() provides simple syntactic sugar around this pattern to make writing this but gets verbose for deeply nested collections: const newObj2 = update(obj,  There is no “right” answer for this. Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times. Others prefer to keep non-critical or UI state, such as “is this dropdown currently open”, inside a component's internal state.


Immutable Update Patterns, These lead to accidental direct mutation, and should be avoided. #Correct Approach: Copying All Levels of Nested Data. Unfortunately, the process of correctly  Composition vs Inheritance React has a powerful composition model, and we recommend using composition instead of inheritance to reuse code between components. In this section, we will consider a few problems where developers new to React often reach for inheritance, and show how we can solve them with composition.