Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
TimWitzdam opened this issue Feb 24, 2024 · 1 comment
Closed

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

TimWitzdam opened this issue Feb 24, 2024 · 1 comment

Comments

@TimWitzdam
Copy link

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
Copy link
Author

I was just stupid...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant