0
function App(){

  const [listState, setListState] = useState([]);

  let connectWebsocket = () => {
    let ws = new WebSocket(`ws://${window.location.host}/ws`);
    ws.onmessage = (event) => {
      let data = JSON.parse(event.data);
      setListState([...listState, data]);
    };
  }

  useEffect(() => {
    console.log(listState); // Problem: This always logs empty array.
  }, [listState]);

  useEffect(() => {
    connectWebsocket();
  }, []);

  return (
    <div>

    </div>
  );
}

When I update state in nested functions, the state is updated to an initial value. How to fix this problem?

ahliru
  • 1
  • 1
  • help us help you, attach the necessary code to debug – scr2em Oct 29 '21 at 12:16
  • 2
    Welcome to Stack Overflow! Nobody can tell you what's wrong with code we can't see. Please provide a [mcve] demonstrating the problem. To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David Oct 29 '21 at 12:19
  • @ahliru: Can you confirm that this is a *React* issue and not a problem with the websocket or the data it returns? If I replace the websocket code with a hard-coded `Promise` to simulate the same "nested function" structure then this works as expected. Could you create a runnable example to demonstrate the specific React problem you're describing? – David Oct 29 '21 at 12:27
  • 1
    `setListState([...listState, data]);` change to `setListState(currentListState => [...currentListState, data]);` -> https://stackoverflow.com/questions/55265255/react-usestate-hook-event-handler-using-initial-state – Tom Finney Oct 29 '21 at 12:27
  • @David I think this is a not problem with the websocket. What do you mean "hard-coded Promise"? – ahliru Oct 29 '21 at 12:34

0 Answers0