@piotar/react-promise-bridge
TypeScript icon, indicating that this package has built-in type declarations

0.4.4 • Public • Published

react-promise-bridge

GitHub package.json version npm (scoped) NPM

A library that allows you to easily manage components that ultimately return a value as a Promise.

This is a simple wrapper that provided the context to resolve or reject the Promise.

This abstract component is designed for dialogs, popups, modals, toasts, dynamic messages, notifications, etc.

It is all up to you.

Installation

npm install @piotar/react-promise-bridge

Features

  • lightweight, no additional dependencies
  • multiple instances and mulitple containers
  • nested containers and nested entries
  • containers can be placed anywhere in other application contexts
  • no additional properties, based on context
  • different types of strategies to create a Promise entry
  • does not require additional changes to existing components, just use the context of the Promise Bridge
  • support AbortSignal
  • function call to open a bridge, works both inside and outside React components

How to use

  1. Import and create container with invoke function of Promise Bridge
// ./SystemPromiseBridge.tsx
import { PromiseBridge } from '@piotar/react-promise-bridge';

// the name of the container and function depends on you
export const [Container, open] = PromiseBridge.create();
  1. Put Container of Promise Bridge wherever you want in the dom React or mount in directly on DOM
// ./main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { App } from './App';
import { Container } from './SystemPromiseBridge';

ReactDOM.createRoot(document.getElementById('root')).render(
    <App>
        {/* ... */}
        <Container />
    </App>,
);

// or directly as DOM element
ReactDOM.createRoot(document.getElementById('modals')).render(<Container />);
  1. Use usePromiseBridge in component to resolve or reject Promise.
// ./Confirm.tsx
import { usePromiseBridge } from '@piotar/react-promise-bridge';

interface ConfirmProps {
    header?: string;
    message: string;
}

export function Confirm({ header, message }: ConfirmProps): JSX.Element {
    const { resolve, reject } = usePromiseBridge<boolean>();

    return (
        <dialog open={true}>
            {header ? <header>{header}</header> : null}
            <p>{message}</p>
            <footer>
                <button type="button" onClick={() => reject(new Error('Canceled'))}>
                    Cancel
                </button>
                <button type="button" onClick={() => resolve(true)}>
                    Confirm
                </button>
            </footer>
        </dialog>
    );
}
  1. Use the invoke Promise Bridge function wherever you want.

Invoke promise bridge function to open component inside React component:

// ./App.tsx
import { open } from './SystemPromiseBridge';

export function App({ children }: React.PropsWithChildren<unknown>): JSX.Element {
    const handleConfirmClick = async () => {
        try {
            await open(<Confirm header="Confirmation" message="Some custom message" />);
            // handle confirm
            console.log('confirmed');
        } catch (error) {
            console.warn(error);
        }
    };

    return (
        <div>
            <button type="button" onClick={handleConfirmClick}>
                Open confirm modal
            </button>
            {/* ... */}
        </div>
    );
}

Invoke promise bridge function to open component outside React:

import { open } from './SystemPromiseBridge';

setTimeout(async () => {
    try {
        const result = await open(<Confirm message="my custom message" />);
        console.log(result);
    } catch (error) {
        console.error(error);
    }
}, 1000);

Try it on:

Open in StackBlitz

Hooks

usePromiseBridge

The main hook for resolving or rejecting Promise.

const { resolve, reject, signal } = usePromiseBridge<ResolveType, RejectType>();

Example in StackBlitz

useDeferredPromiseBridge

A hook based on usePromiseBridge.

The hook is designed to manage animation.

The hook allows you to defer the fulfilled Promise and release it by calling a trigger function.

const {
    resolve,
    reject,
    signal,
    state,
    trigger,
    Provider,
} = useDeferredPromiseBridge<ResolveType, RejectType>();

Example in StackBlitz

useDisposePromiseBridge

The helper hook is designed to help create an abort controller to reject Promise after the trigger component is destroyed.

const abortController = useDisposePromiseBridge(signals);

Example in StackBlitz

useFactoryPromiseBridge

A helper hook for creating a new Promise Bridge instance for dynamic React components.

const [Container, opener] = useFactoryPromiseBridge(options);

Example in StackBlitz

Examples

Repository example Open in StackBlitz
#01 Basic Open in StackBlitz
#02 Animation Open in StackBlitz
#03 Animation with classes Open in StackBlitz
#04 Abort controller Open in StackBlitz
#05 Entry with strategy recreate Open in StackBlitz
#06 Entry with strategy reject if exists Open in StackBlitz
#07 Multicontainer Open in StackBlitz
#08 Destroy Bridge after destroy trigger component Open in StackBlitz

Integrations with UI libraries

Repository example Open in StackBlitz
#i01 Material UI (MUI) Open in StackBlitz
#i02 React Bootstrap Open in StackBlitz
#i03 Ant design (antd) Open in StackBlitz

Package Sidebar

Install

npm i @piotar/react-promise-bridge

Weekly Downloads

1

Version

0.4.4

License

MIT

Unpacked Size

41.7 kB

Total Files

50

Last publish

Collaborators

  • piotar