0.0.3 • Published 1 year ago

react-broadcast-channels v0.0.3

Weekly downloads
-
License
-
Repository
github
Last release
1 year ago

react-broadcast-channels

A React hook for using BroadcastChannel API for seamless communication between components.

Installation:

npm install react-broadcast-channels

or

yarn add react-broadcast-channels

Usage:

1. Global Application Behavior (App.js):

This example demonstrates using react-broadcast-channels in your root App.js file to manage global application state updates on login and logout events.

import React from 'react';
import { useBroadCast } from 'react-broadcast-channels';

const App = () => {

  const [currentUser, setCurrentUser] = useState(null);
  const logoutCallback = () => {
    logout(); // Implement your logout logic here
    document.title = "App Name";
  };

  const loginCallback = (event) => {
    document.title = "App Name";
    setCurrentUser(event.data.data); // Update user state
    navigate(url); // Navigate to dashboard
  };

  useBroadCast(logoutCallback, loginCallback);

  // ... the rest of your App component
};

export default App;

2. Modular Approach (Dedicated Context):

For more complex applications, consider creating a dedicated Context Provider to encapsulate useBroadCast usage and related functions for specific sections like authentication.

import React from 'react';
import { createContext, useContext, useState } from 'react';
import { useBroadCast } from 'react-broadcast-channels';

const AuthContext = createContext();

const AuthProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);

  const logoutCallback = () => {
    logout(); // Implement your logout logic here
    document.title = "App Name";
  };

  const loginCallback = (event) => {
    document.title = "App Name";
    setCurrentUser(event.data.data);
  };

  const { loginChannel, logoutChannel } = useBroadCast(logoutCallback, loginCallback);

  return (
    <AuthContext.Provider value={{ currentUser, loginChannel, logoutChannel }}>
      {children}
    </AuthContext.Provider>
  );
};

// In other components:
const MyComponent = () => {
  const { currentUser, loginChannel, logoutChannel } = useContext(AuthContext);

  // ... use loginChannel and logoutChannel for login/logout functionality
};

export default AuthProvider;

3. Login Component Integration (login.jsx):

import React, { useState } from 'react';
import { useBroadCast } from 'react-broadcast-channels';

const Login = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const { loginChannel } = useBroadCast();

  const handleLogin = async () => {
    // Implement your login logic here, e.g., send a request to your backend
    const response = await fetch('/api/login', {
      method: 'POST',
      body: JSON.stringify({ username, password }),
    });

    if (response.ok) {
      const loginData = await response.json();
      loginChannel.postMessage({
        type: 'login',
        data: loginData,
      });
    } else {
      // Handle login errors
    }
  };

  return (
    <form onSubmit={handleLogin}>
      {/* ... login form fields ... */}
      <button type="submit">Login</button>
    </form>
  );
};

export default Login;

4. Logout Component Integration (logout.jsx):

import React, { useEffect } from 'react';
import { useBroadCast } from 'react-broadcast-channels';

function Logout() {
  const { logoutChannel } = useBroadCast();

  useEffect(() => {
    logout(); // Implement your logout logic here
    logoutChannel.postMessage({ type: "logout" });
  }, [logoutChannel]);

  return <Outlet />; // Assuming you're using a routing library for navigation
}

export default Logout;

Features:

  • Simple and intuitive API, mirroring the Browser BroadcastChannel API.
  • Decouples component communication, increasing maintainability and reusability.
  • Lightweight and efficient, utilizing native browser support.
  • Compatible with multiple tabs and windows, ideal for real-time applications.

Benefits:

  • Centralized Communication: Manage state updates and event handling across various components seamlessly.
  • Improved Modularity: Separate concerns and promote code organization through clear communication channels.
  • Enhanced Reactivity: Enable components to react dynamically to events broadcasted across the application.
  • Efficient State Management: Reduce complexity and optimize state updates.

Limitations:

  • Requires browser support for the BroadcastChannel API (available in most modern browsers).
  • Messages are limited to primitive data types or JSON-serializable objects.
  • Security considerations: ensure messages are properly validated and sanitized to prevent vulnerabilities.

License:

MIT

Contributions:

Welcome! Fork the project and submit pull requests to contribute to its growth and improvement.

Get started today and elevate your React applications with efficient and centralized communication using react-broadcast-channels!

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago