1

I am trying to update a state after a trigger and want to use the state immediately for a function to trigger but the state is not updated immediately .

any suggestions ?

                 <Button
                       onClick={() => {
                        console.log(finalData) //old data
                       setFinalData(mutableData); // updating state
                        console.log(finalData) // still geeting old state
               }>
           </Button>
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Bhart Supriya
  • 262
  • 4
  • 16
  • 1
    Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Martin May 15 '20 at 06:24

1 Answers1

6

setFinalData is kind of async behaviour, so if you :

console.log(finalData) //old data
setFinalData(mutableData); // <----- async behavior
console.log(finalData) // you will never get updated finalData directly here

Solution : useEffect

useEffect(() => {
    // you will get updated finalData here, each time it changes
    console.log(finalData);
    // you can trigger your function from here
},[finalData]);

Here is code snippet, hope this will clear your doubts :

const { useState , useEffect } = React;

const App = () => {

  const [finalData,setFinalData] = useState([]);

  useEffect(() => {
    setTimeout(() => {
      setFinalData([...finalData, "Vivek" , "Darshita"]);
      console.log("finalData -----> not updated right after" ,finalData);
    },2000);
  },[]);

  useEffect(() => {
    if(finalData.length)
      console.log("Final data updated , invoke your function" , finalData)
  },[finalData]);

  return (
    <div>
      { finalData.map(user => <p>{user}</p>) }
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122