react setstate not updating state

  • Last Update :
  • Techknowledgy :

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. If you work with funcions you need to use UseEffect to deal with setState's asynchrony (you can't use the callback as you did when working with classes). An example: 1 I had completely forgot the fact that it's async call and did all possible code changes except for this one and here you saved my brain from burning out. thanks – Hem M Nov 4, 2020 at 13:22

This is our Splunktool team suggestion, we tried and its working fine ✌
this.setState({
   pencil: !this.state.pencil
}, myFunction)​

setState() is usually asynchronous, which means that at the time you console.log the state, it's not updated yet. Try putting the log in the callback of the setState() method. It is executed after the state change is complete:

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

In case of hooks, you should use useEffect hook.

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

setFruit('Apple');

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

Suggestion : 2

React this.setState, and useState does not make changes directly to the state object. React this.setState, and React.useState create queues for React core to update the state object of a React component. Let’s dive into why this.setState and React.useStatedo not update immediately. Does it feel like when you call this.setState or React.useState, the changes feel like it’s a step behind?

If you’re using a class component, you will have to usethis.setState() to update the state of a React component.

this.setState(state, callback);

The second parameter this.setState() accepts is the callback function, and that’s where you’ll want to add your side effects.

This callback function will get triggered when React state has finished updating.

this.setState(newStateObject, () => {
   // ... do some other actions
});

The example above uses the arrow function, but you can do it with a traditional function syntax.

this.setState(newStateObject, function() {
   // ... do some other actions
});

That hook function will only activate if the values in the list change.

Let’s take a look at an example

let s;

const Foo = () => {
  const [counter, setCounter] = React.useState(0);

  // Emmulate componentDidMount lifecycle
  React.useEffect(() => {
    s = setInterval(() => {
      setCounter(state => (state +1));
    }, 1000);
  }, []);

  // This is for counter state variable
  React.useEffect(() => {
    if (counter > 9) {
      clearInterval(s);
    }
  }, [counter]);

  return <span>{counter}</span>;
};

Suggestion : 3

State updates in React are asynchronous; when an update is requested, there is no guarantee that the updates will be made immediately. The updater functions enqueue changes to the component state, but React may delay the changes, updating several components in a single pass. The componentDidUpdate function is invoked immediately after a state update occurs. To avoid an infinite loop, you should always use a conditional statement to be sure that the previous state and the current state are not the same: Now that we’ve established that delaying reconciliation of updates requests in order to batch them is beneficial, there are also times when you need to wait on the updates to do something with the updated values. In the next section, we’ll see how to do that.

For example, consider the code below:

//React
const handleClick = () => {
   setName("Amaka")
   setAge(20)
   setAddress("No 3 Rodeo drive")
}

The second parameter to setState() is an optional callback function. This argument will be executed once setState() is completed and the component is re-rendered. The callback function is guaranteed to run after the state update has been applied:

//React

handleSearch = (e) => {
   this.setState({
      searchTerm: e.target.value
   }, () => {
      // Do an API call with this.state.searchTerm
   });
}
3._
//React

componentDidUpdate(prevProps, prevState) {
   if (prevState.count !== this.state.count) {
      // Do something here
   }
}

Suggestion : 4

The reason why the state doesn’t update immediately is because for each render, the state is immutable. Plenty of articles have been written about this saying setState is asynchronous. This may sounds probable but it isn’t the exact reason why your state doesn’t update immediately. …are both constants values ! So they’re immutable. The state remains constant inside the render but can be changed between two renders. The same goes for dispatch and useReducer. but this is actually normal, just as expected. The component has to rerender before updating the new state.

1._
function onClick() {
   //let's say last state was 1
   setSomeState(2)
   console.log(someState); //will log 1 but not 2
}
2._
function App(){

    const [count, setCount] = useState(1);

    function onClick(){
        setCount(count + 1)
        console.log(count);  
    // First time the button is clicked this will log 1, not 2
    // This console logged count will always "lag behind"
    }

    console.log(count) 
    //This will log 1 on first render 
    //before clicking the button.
    //After the first button click, the state 
    //will be updated which triggers a second 
    //render and then this will log 2

    return(
    <button onClick={onClick}>increment count</button>
    )
	
}
3._
function onClick() {
   await setCount(count + 1) //not possibile
   console.log(count); //logs 2
}
5._
//Instead of this:

function onChange() {
   setCount(count + 1);
   getData(count);
   //here count is not equal to the state 
   //you just set, it's the previous state
}

//Do this:
function onChange() {
   const newCount = count + 1;
   setCount(newCount);
   getData(newCount);
   //now you can be sure you call getData
   //with the state you just set
}
6._
useEffect(() => {
   getData(count);
}, [count])

Suggestion : 5

Many examples helped us understand how to fix the Setstate Not Updating State Immediately error. Hello everyone, in this post we will look at how to solve the Setstate Not Updating State Immediately problem in the programming language. Setstate Not Updating State Immediately With Code Examples React Native Load Function Each Time Visit Screen With Code Examples

1._
//In case of hooks, you should use useEffect hook.
const [fruit, setFruit] = useState('');

setFruit('Apple');

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

Using a different strategy, which is described below with code samples, the identical issue Setstate Not Updating State Immediately can be resolved.

myFunction = () => {
   this.props.updateItem(this.state)
}

Suggestion : 6

To update the state of a component, you use the setState method. However it is easy to forget that the setState method is asynchronous, causing tricky to debug issues in your code. The setState function also does not return a Promise. Using async/await or anything similar will not work. Use the useEffect hook to wait for state to update in React. You can add the state variables you want to track to the hook’s dependencies array and the function you pass to useEffect will run every time the state variables change.30-Apr-2022 When you directly update the state, it does not change this. state immediately. Instead, it creates a pending state transition, and accessing it after calling this method will only return the present value. You will lose control of the state across all components.

In this session, we’ll try our hand at solving the React State Not Updating Immediately puzzle by using the computer language. The code that is displayed below illustrates this point.

//In case of hooks, you should use useEffect hook.
const [fruit, setFruit] = useState('');

setFruit('Apple');

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

One can solve the same problem using a variety of different strategies React State Not Updating Immediately. There is no one right way to do it. In the paragraphs that follow, we will discuss the many different alternatives to the current problem.

myFunction = () => {
   this.props.updateItem(this.state)
}

Suggestion : 7

setState() schedules an update to a component’s state object. When state changes, the component responds by re-rendering. Passing an update function allows you to access the current state value inside the updater. Since setState calls are batched, this lets you chain updates and ensure they build on top of each other instead of conflicting: Calls to setState are asynchronous - don’t rely on this.state to reflect the new value immediately after calling setState. Pass an updater function instead of an object if you need to compute values based on the current state (see below for details).

1._
incrementCount() {
   // Note: this will *not* work as intended.
   this.setState({
      count: this.state.count + 1
   });
}

handleSomething() {
   // Let's say `this.state.count` starts at 0.
   this.incrementCount();
   this.incrementCount();
   this.incrementCount();
   // When React re-renders the component, `this.state.count` will be 1, but you expected 3.

   // This is because `incrementCount()` function above reads from `this.state.count`,
   // but React doesn't update `this.state.count` until the component is re-rendered.
   // So `incrementCount()` ends up reading `this.state.count` as 0 every time, and sets it to 1.

   // The fix is described below!
}
2._
incrementCount() {
   this.setState((state) => {
      // Important: read `state` instead of `this.state` when updating.
      return {
         count: state.count + 1
      }
   });
}

handleSomething() {
   // Let's say `this.state.count` starts at 0.
   this.incrementCount();
   this.incrementCount();
   this.incrementCount();

   // If you read `this.state.count` now, it would still be 0.
   // But when React re-renders the component, it will be 3.
}

Suggestion : 8

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state. React may batch multiple setState() calls into a single update for performance. While this.props is set up by React itself and this.state has a special meaning, you are free to add additional fields to the class manually if you need to store something that doesn’t participate in the data flow (like a timer ID). It will use this.setState() to schedule updates to the component local state:

1._
const root = ReactDOM.createRoot(document.getElementById('root'));
  
function tick() {
  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
    </div>
  );
  root.render(element);}

setInterval(tick, 1000);
2._
const root = ReactDOM.createRoot(document.getElementById('root'));

function Clock(props) {
  return (
    <div>      <h1>Hello, world!</h1>      <h2>It is {props.date.toLocaleTimeString()}.</h2>    </div>  );
}

function tick() {
  root.render(<Clock date={new Date()} />);}

setInterval(tick, 1000);
3._
root.render(
<Clock />);
5._
class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>      </div>
    );
  }
}
6._
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}