Search code examples
reactjslaravelwebsocketpusherlaravel-echo

Laravel Echo stops listening events after unmounting and mounting again a react component


I've already connected Laravel Echo. I use Pusher and ReactJS and put connection to the private channel to componentDidMount() method:

componentDidMount() {
    let channelName = 'channel.12345';
    let eventName = '.RoshamboResults.54321';

    Echo.private(channelName)
      .listen(eventName, data => {
        console.log('Socket', data);
      });
  }

It works until I go to another route, so the app unmounts the component. When I go back and wait for another message from the channel I can see it in the Inspect -> Network -> WebSockets only, but not in the console log. So JS stopped listening to it.


Solution

  • Maybe you should put a console on your componentWillUnmount and componentDidMount life-cycles in your component, do the steps again, and see if your component is indeed getting unmounted when you route, and mounted when you come back.

    Possibly your component is not getting unmounted at all, and so your componentDidMount is probably working only once. I think that is most likely the issue.

    Looking into the react life-cycles deeply might also help your issue, if what I said above is the case. Here is an article I have found quite explanatory about the life cycles. The react documentation is also quite good. Hope this helps. :)

    https://levelup.gitconnected.com/componentdidmakesense-react-lifecycle-explanation-393dcb19e459