Coder Social home page Coder Social logo

guptasiddhant / react-broadcast-channel Goto Github PK

View Code? Open in Web Editor NEW
16.0 2.0 3.0 210 KB

React hooks for accessing web broadcast channel API.

Home Page: https://npm.im/use-broadcast-channel/

License: MIT License

TypeScript 94.21% HTML 5.79%
react hooks broadcast channel use

react-broadcast-channel's Introduction

use-broadcast-channel (React-hooks)

The Broadcast Channel API allows basic communication between browsing contexts (that is, windows, tabs, frames, or iframes) and workers on the same origin. -MDN

This package provides a thin wrapper around the browser's native Broadcast Channel API in the form of a React hook function. The hook(s) can be used in any React component or custom hook to harness the functionality of Broadcast Channel API.

To use the hooks in browsers that do not support Broadcast Channel API, install and import broadcastchannel-polyfill.

For typescript users: The default data-type for all messages are set to string but can be easily overridden by explicitly passing type parameter to the hook(s). Example for numeric data: useBroadcastChannel<number>("count", (e) => console.log(e.data));

Setup

Package available at NPM.

  • NPM

    npm install use-broadcast-channel
  • Yarn

    yarn add use-broadcast-channel

API

The package exports multiple hooks for different use-cases.

useBroadcastChannel hook

React hook to create and manage a Broadcast Channel across multiple browser windows/tabs/frames. This is base hook exported by the package as all other exported hooks depends on it.

- Read-only

Only subscribe for events broadcasted on a particular channel.

import { useBroadcastChannel } from "use-broadcast-channel";

function App() {
  useBroadcastChannel("userId", (e) => alert(e.data));
  return null;
}

- Write-only

Only broadcast (post) event on a particular channel.

import { useBroadcastChannel } from "use-broadcast-channel";

function App() {
  const postUserId = useBroadcastChannel("userId");
  return <button onClick={() => postUserId("ABC123")}>Post UserId</button>;
}

- Read and Write

Both broadcast (post) event and subscribe for events broadcasted on a particular channel.

import { useBroadcastChannel } from "use-broadcast-channel";

function App() {
  const postUserId = useBroadcastChannel("userId", (e) => alert(e.data));
  return <button onClick={() => postUserId("ABC123")}>Send UserId</button>;
}

useBroadcastState hook

React hook to manage state across browser windows/tabs/frames. It has a similar signature as React.useState. It used useBroadcastChannel under the hood.

import { useBroadcastState } from "use-broadcast-channel";

function App() {
  const [count, setCount] = useBroadcastState("count", 0);
  return (
    <div>
      <button onClick={() => setCount((prev) => prev - 1)}>Decrement</button>
      <span>{count}</span>
      <button onClick={() => setCount((prev) => prev + 1)}>Increment</button>
    </div>
  );
}

react-broadcast-channel's People

Contributors

guptasiddhant avatar nikeee avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

react-broadcast-channel's Issues

typescript error using library

Hi, firs of all thanks for writing a fantastic lib.

When importing the lib I keep getting the following typescript error:

Could not find a declaration file for module 'use-broadcast-channel'. '.../node_modules/use-broadcast-channel/dist/index.cjs' implicitly has an 'any' type.
  Try `npm i --save-dev @types/use-broadcast-channel` if it exists or add a new declaration (.d.ts) file containing `declare module 'use-broadcast-channel';`ts(7016)

I saw in the build script that there is a tsc command to generate a d.ts but I'm unable to find it in the ./dist folder.

I think the issue is that the file is indeed generated but output to ./dist/src/index.d.ts and thereby not resolved.

manually moving the file worked for me so I guess it's a minor tweak to the tsconfig.json file needed.

Will try to fix and submit a PR

The requested module does not provide an export named 'default'

Hi! I have got this error when I run the app.

Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/use-broadcast-channel.js?v=3a2c67f1' does not provide an export named 'default' (at NotificationRequest.tsx:15:1)

How I try to use it

import { useBroadcastChannel } from "use-broadcast-channel";

function SubChange() {
  useBroadcastChannel("testBroadcast", async function (e: any) {
    try {
      const resp = await api.post("/test", {
        subscription: JSON.stringify(e.detail.subData),
      });
      console.log(resp);
    } catch (e) {
      console.error(e);
    }
  });
  return null;
}

I have installed the latest with npm

Also in the package.json file I got a 0.1.3 version and not a 1.0.3

"use-broadcast-channel": "^0.1.3",

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.