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

空扰寡人 提交于 2021-01-29 18:17:31

问题


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

/*- - - -after updation - - - >*/
    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");
  };

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


回答1:


The new set state value will only be available on the next render. I would suggest using useeffect. Or you could use useReducer instead. That would work too



来源:https://stackoverflow.com/questions/63623412/wait-for-state-to-update-using-usestate-hook-and-then-run-code-inside-a-funciton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!