Skip to content

πŸ”ŒπŸ“¨ Implementation of BroadcastChannel API in react to emit and subscribe any messages to a particular channel.

License

Notifications You must be signed in to change notification settings

jhony-v/react-broadcast-channel

Repository files navigation

React broadcast channel

last commit version size licence code

Implementation of BroadcastChannel API in react to emit and subscribe any messages to a particular channel.

DEMO

Installation

To install, you can use npm or yarn:

$ npm install react-web-broadcast-channel
$ yarn add react-web-broadcast-channel

Examples

If you open other tab in your browser, you cant see how the message sent is updated in all tabs.

import React from 'react';
import { useBroadcastChannelEmitter } from "react-web-broadcast-channel"


const TEST_CHANNEL = "TEST_CHANNEL";

export default function App() {
  const { emit, data } = useBroadcastChannelEmitter(TEST_CHANNEL);

  const sendMessage = () => {
    emit(prompt())
  }


  return(
    <div>
      <button onClick={sendMessage}>emit event</button>
      <h1>{data}</h1>
    </div>
  )
}

Emiting messages to channel

import { useEffect } from "react";
import { 
  BroadcastSubscriber, 
  BroadcastEmiter, 
  useBroadcastChannelEmitter 
} from "react-web-broadcast-channel";

function EmitMessageFromA() {
    const { emit } = useBroadcastChannelEmitter(TEST_CHANNEL);
    
    const sendMessage = () => {
      emit(prompt())
    }

    return <button onClick={sendMessage}>send message from a</button>
}

function EmitMessageFromB() {
    return(
     <BroadcastEmiter channel={TEST_CHANNEL}>
       {(emit) => {
         return <button onClick={() => emit(prompt()) }>
           send message from b
         </button>    
       }}
     </BroadcastEmiter>
    )
}

Suscribe a channel

import { BroadcastSubscriber, useBroadcastChannelSubscribe } from "react-web-broadcast-channel";

function SubscriberA() {
  const { data } = useBroadcastChannelSubscribe(TEST_CHANNEL);
  useEffect(() => {
    console.log(data)
  },[data])

  return <div>Subscribe from A</div>
}

function SubscriberB() {
  return(
   <BroadcastSubscriber channel={TEST_CHANNEL}>
    {(data) => (
      <div>{data}<div>
    )}
   </BroadcastSubscriber>
  ) 
}

About

πŸ”ŒπŸ“¨ Implementation of BroadcastChannel API in react to emit and subscribe any messages to a particular channel.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published