tanmay
tanmay

Reputation: 51

Wait for State to update using UseState hook and then run code inside a function

const startLive = () => {
    // connect to websocket only on start button
    
     setliveChartState({
      ...liveChartState,
      liveActive: !liveChartState.liveActive,
      historicLiveActive: true,
      start: new Date(),
    });

/*- - - -after updation this code needs to run - - - >*/
    const { ws, liveActive } = liveChartState;
    
    // if clicked on stop then close websocket
    if (!liveActive && ws) {
      ws.close();
    clearLiveInterval();
    }
    // if clicked on  start and websocket close then connect
    if ((!ws || ws.readyState === WebSocket.CLOSED)&& liveActive) connect();
    fetchData("historic");

/*----------*/
  };

I have a functional component

The startlive function gets called when start button is clicked... This function is used to update the state and then execute the code which comes later as mentioned.

But it runs when setlivechartstate has not even completeted the updation.

I do not want to use Use effect hook as i just want to run the code only when button is clicked as it is working both as start and stop and also liveActive is getting changed in other functions also.. So using useEffect with this dependency created problem

What is the best way i can make this function work and only run the code after the updation is done

Upvotes: 0

Views: 80

Answers (2)

viveknigam3003
viveknigam3003

Reputation: 66

Considering your use case it would be great if you have a look at async/await functions and JavaScript Promises. In my opinion a good way to perform the update will be to maybe wrap your setliveChartState() function inside an async function, something like:

async function setLiveChart() {
   setliveChartState(...)
}

And then call your async setLiveChart() function inside your const startLive = () => {} like:

const startLive = () => {
    // connect to websocket only on start button
    
     setLiveChart().then(() => {

     /*- - - -after updation this code needs to run - - - >*/
    const { ws, liveActive } = liveChartState;
    
    // if clicked on stop then close websocket
    if (!liveActive && ws) {
      ws.close();
    clearLiveInterval();
    }

    // if clicked on  start and websocket close then connect
    if ((!ws || ws.readyState === WebSocket.CLOSED)&& liveActive) connect();
    fetchData("historic");

   /*----------*/
  }
};

You can also chain multiple then() callbacks like

setLiveChart()
  .then(() => {})
  .then(() => {})
  .then...

Upvotes: 0

Nidhi Dadiya
Nidhi Dadiya

Reputation: 839

It would be better if you use useEffect. and for your issue you can check inside useEffect that if button is clicked : true then only useEffect will execute your updation code.

useEffect(() => {
 if (ButtonClicked) {
   // do updation stuff
  }
}, [ButtonClicked]);

Upvotes: 1

Related Questions