问题
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