0

I am using laravel-websockets to listen to event. I have no issue on the back-end side; The issue is on the front-end side.

SCENARIO:

When I go to a specific route post/[slug], the current channel is based on the current slug. When I redirect to the same route but different value of slug, the channel listens to the first value on page refresh and not to the current one.

const Component = () => {
  const router = useRouter();
  const {slug} = router.query;

  useEffect(() => {
   window.Echo.private(`post.${slug}`).listen('PrivateEvent', e => { 
    console.log(e)
   });
  }, [slug])
}

Example:

On page refresh, go to post/first-slug. Next, click to <Link to="/post/second-slug">About</Link>

The example above should listen to second-slug and not the first-slug.

How can I solve this without hard refresh or <a> tag?

smzapp
  • 809
  • 1
  • 12
  • 33

1 Answers1

1

You forgot to stop listening on the previous channel, so the events are still received. I suppose that you end up with two active channels, receiving events for both.

Inside a useEffect() you should return a cleanup function that clears resources created for the effect

Here is how:

const Component = () => {
  const router = useRouter();
  const {slug} = router.query;

  useEffect(() => {
   window.Echo.private(`post.${slug}`).listen('PrivateEvent', e => { 
    console.log(e)
   });

   return () => window.Echo.private(`post.${slug}`).stopListening('PrivateEvent');
  }, [slug])
}

If this does not solve your problem, please:

  • display the slug in your component (return <div>slug</div>;) to confirm that the navigation really happens ;
  • show us the whole console log.
Caerbannog
  • 790
  • 3
  • 8