0

I have created a simple chat app wherein a user may send a message privately. Now, while the page is on first load (mounted), the console logs only one line. If I click on other links (not hard refresh) and go back to the page, the console logs multiple times.

Using ReactJS

useEffect(() => {
   window.Echo.private(`chat`).listen('PrivateMessageEvent', e => { 
    console.log(e) // this logs multiple times
   });
}, []);

If using VueJS

mounted() {
   window.Echo.private(`chat`).listen('PrivateMessageEvent', e => { 
    console.log(e) // this logs multiple times
   });
}

Example:

When I visit page /first-link, this logs only one line.

Then, if go to /second-link (<router-link> for vuejs / <Link /> for reactjs) , then /third-link and go back to /first-link, the console logs multiple times.

I notice that the Echo listens multiple times. How can I fix this?

smzapp
  • 809
  • 1
  • 12
  • 33

1 Answers1

0

Reason

This issue occurs when a component is re-rendered when visiting other routes.

Solution

When I put the window.Echo on child component, the Echo listens many times based on the number of visits. That's why, I put it at the uppermost / parent component so that it won't re-render the component.

As much as possible, I put it at the _app.js level.

smzapp
  • 809
  • 1
  • 12
  • 33