React with BroadcastChannel

2.3k Views Asked by At

In the React app I click on button to open new tab. When I open new tab I want to pass some data to the new tab.

Code from my button component

const channel = new BroadcastChannel('color');

const handleClick = () => {
 ...
 channel.postMessage('GREEEENNNNNNNNN');
}

Code from new tab component

const [color, setColor] = React.useState('');

const channel = new BroadcastChannel('color');
  React.useEffect(() => {
    channel.onmessage = (msg) => setColor(msg.data);
  }, [channel]);

  console.log('color <========', color); // just to see that this is working

What I expect: I see 'GREEEENNNNNNNNN' in the console in new tab

What happening:

  1. If I open only one new tab, I DON'T see 'GREEEENNNNNNNNN' in the console
  2. If I open another new tab, I can see 'GREEEENNNNNNNNN' in the console of the first tab

Question: How to broadcast this value to new tab?

1

There are 1 best solutions below

0
On

To declare the Chanel

const channel = useMemo(() => new BroadcastChannel('color'), []);

To receive message

useEffect(() => {
        channel.addEventListener('message', (event) => {
             setColor(msg.data.color);

        });
    }, []);

To send message

channel.postMessage({
            color: 'red'
        });