[javascript] React setState not updating state

So I have this:

let total = newDealersDeckTotal.reduce(function(a, b) {
  return a + b;
},
0);

console.log(total, 'tittal'); //outputs correct total
setTimeout(() => {
  this.setState({dealersOverallTotal: total});
}, 10);

console.log(this.state.dealersOverallTotal, 'dealersOverallTotal1'); //outputs incorrect total

newDealersDeckTotal is just an array of numbers [1, 5, 9] e.g. however this.state.dealersOverallTotal does not give the correct total but total does? I even put in a timeout delay to see if this solved the problem. any obvious or should I post more code?

This question is related to javascript reactjs state setstate

The answer is


I had the same situation with some convoluted code, and nothing from the existing suggestions worked for me.

My problem was that setState was happening from callback func, issued by one of the components. And my suspicious is that the call was occurring synchronously, which prevented setState from setting state at all.

Simply put I have something like this:

render() {
    <Control
        ref={_ => this.control = _}
        onChange={this.handleChange}
        onUpdated={this.handleUpdate} />
}

handleChange() {
    this.control.doUpdate();
}

handleUpdate() {
    this.setState({...});
}

The way I had to "fix" it was to put doUpdate() into setTimeout like this:

handleChange() {
    setTimeout(() => { this.control.doUpdate(); }, 10);
}

Not ideal, but otherwise it would be a significant refactoring.


setState is asynchronous. You can use callback method to get updated state.

changeHandler(event) {
    this.setState({ yourName: event.target.value }, () => 
    console.log(this.state.yourName));
 }

I had an issue when setting react state multiple times (it always used default state). Following this react/github issue worked for me

const [state, setState] = useState({
  foo: "abc",
  bar: 123
});

// Do this!
setState(prevState => {
  return {
    ...prevState,
    foo: "def"
  };
});
setState(prevState => {
  return {
    ...prevState,
    bar: 456
  };
});

The setState() operation is asynchronous and hence your console.log() will be executed before the setState() mutates the values and hence you see the result.

To solve it, log the value in the callback function of setState(), like:

setTimeout(() => {
    this.setState({dealersOverallTotal: total},
    function(){
       console.log(this.state.dealersOverallTotal, 'dealersOverallTotal1');
    });
}, 10)

In case of hooks, you should use useEffect hook.

const [fruit, setFruit] = useState('');

setFruit('Apple');

useEffect(() => {
  console.log('Fruit', fruit);
}, [fruit])

Using async/await

async changeHandler(event) {
    await this.setState({ yourName: event.target.value });
    console.log(this.state.yourName);
}

just add componentDidUpdate(){} method in your code, and it will work. you can check the life cycle of react native here:

https://images.app.goo.gl/BVRAi4ea2P4LchqJ8


The setstate is asynchronous in react, so to see the updated state in console use the callback as shown below (Callback function will execute after the setstate update)

enter image description here

The below method is "not recommended" but for understanding, if you mutate state directly you can see the updated state in the next line. I repeat this is "not recommended"

enter image description here


As well as noting the asynchronous nature of setState, be aware that you may have competing event handlers, one doing the state change you want and the other immediately undoing it again. For example onClick on a component whose parent also handles the onClick. Check by adding trace. Prevent this by using e.stopPropagation.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to state

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter? Updating an object with setState in React Why can't I change my input value in React even with the onChange listener React setState not updating state How to use onClick with divs in React.js React - how to pass state to another component React.js, wait for setState to finish before triggering a function? setInterval in a React app React: how to update state.item[1] in state using setState? AngularJS ui router passing data between states without URL

Examples related to setstate

Can't perform a React state update on an unmounted component How to update nested state properties in React When to use React setState callback React setState not updating state ReactJS: Warning: setState(...): Cannot update during an existing state transition Can I execute a function after setState is finished updating?