简体   繁体   中英

BroadcastChannel sometime not listening at useEffect

I am facing a problem that the broadcast channel is not listening sometime in useEffect . There is some list and upon clicking individual item, the broadcast postmessage should be emitting message to the listener of another file. Sometime it's working but for some reason, it's not receiving that event.

This snippet is located at index.js. Upon changes happened in dependencies, I am getting debug message all the time however it's not going inside onMessage .

useEffect(() => {
    const messageBus = new BroadcastChannel('channelABC');
    console.debug("ITS COMING HERE ALL THE TIME");
    const onMessage = ({ data: message }) => {
      if (message.type === 'ABCFired') {
        showABC(message);
      }
    };

    messageBus.addEventListener('message', onMessage);

    return () => {
      messageBus.removeEventListener('message', onMessage);
      messageBus.close();
    };

  }, [dependencies]);

This is another file where message is being emitted.

const onRowClicked = index => {
    setId(oldId => {
          if (oldId !== index) {
            console.debug("ITS ALSO WORKING");
            messageBus.postMessage({ type: 'ABCFired', message });
            return index;
          }
          else {
            return null;
          }
        });
  };

I am searching through the same answer right now. I have found that maybe when the broadcast channel shoots a message, the component gets unmount and the event listener is removed.

So by the time the message is fired, there is no listener.

Make a console statement in return function of use effect called

console.log('unmount)

You already have a console in onRowClicked, so check when you fire, onRowClicked, do you get unmount after that or something.

Quickfix Remove the dependency from use Effect. In your case you want to enable eventListner once the app starts, I think.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM