Search code examples
reactjsstatepusherpusher-js

Outdated react state in pusher .bind method


I use pusher-js to receive data from the backend.


I configure it in useEffect like this:

  useEffect(() => {
    const pusher = new Pusher('my_app_id', {
      cluster: 'us3',
    });

    const channel = pusher.subscribe('messages');

    channel.bind('send-message', (data) => {

    });
  }, []);

In the callback of the .bind method, I want to access the react state. The problem is, that if it gets updated, this callback still has the old version.

channel.bind('send-message', (data) => {
    // here is my outdated state
});

How can I acces new, updated state inside this callback? Thanks in advance


Solution

  • Use another useEffect with the updated state in your dependency array of the useEffect,as soon as the state gets updated that useEffect will. be triggered and inside it you can access the updated state.