apteryxxyz / next-ws

Add support for WebSockets in Next.js app directory.
https://npmjs.com/next-ws
171 stars 12 forks source link

Using useState inside onMessage (from the client example) #21

Closed TimWitzdam closed 7 months ago

TimWitzdam commented 7 months ago

Hello, I was wondering how you can change a state inside the onMessage callback, since by default it's using a wrong reference of whatever state you place inside it.

Do you know any workaround for that?

I've changed up your example a bit, did it break something, that I'm not aware of?


const onMessage = useCallback((event: MessageEvent) => {
    setMessage(event.data); // This doesn't work/updates the real state
    console.log("Message from server ", event.data);
  }, []);

  useEffect(() => {
    ws?.addEventListener("message", onMessage);
    return () => ws?.removeEventListener("message", onMessage);
  }, [onMessage, ws]);
TimWitzdam commented 7 months ago

I was just stupid...