suspense-utils
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

Suspense Utils

Demo app Bundle size Support semantic-release Conventional Commits

A small library with utils that make working suspense easy as well as an error boundary that can be used so that components can have error, loading and data states.

Install

yarn add suspense-utils

Suspense

Tools used to help with suspense itself

Create Repository

This utility method is used to create a data loader that caches each request.

This requires React 16.6+

This is an example using a fetch request and a public api.

import { createRepository } from 'suspense-utils';

const dataResolver = async (searchTerm: string) => {
    const response = await fetch(`https://api.publicapis.org/entries?title=${searchTerm}`);
    const data = await response.json();

    return data;
}

export const repository = createRepository(dataResolver);

Here is a second example that asynchronously loads an svg based on an enum value.

import { createRepository } from 'suspense-utils';

export const repository = createRepository(async (sprite: SpriteType) => {
    let spritePromise: () => Promise<DynamicImportType>;

    switch (sprite) {
        case SpriteType.Sun:
            spritePromise = () => import('../svg/sun');
            break;
        case SpriteType.Thermo:
            spritePromise = () => import('../svg/thermo');
            break;
        case SpriteType.Wind:
            spritePromise = () => import('../svg/wind');
            break;
        case SpriteType.Rain:
            spritePromise = () => import('../svg/rain');
            break;
        default:
            throw new Error(`Missing implementation for ${sprite} in sprite repository`);
    }

    const resolvedModule = await spritePromise();
    return resolvedModule.default;
})

HOC

This is a wrapper that aims to keep things simple by creating a component with a loading state and error state built in that can handle repositories.

This requires React 16.8+

import { SuspenseComponent } from 'suspense-utils';
import { repository } from '../repositories';

const LayoutComponent: React.FC<LayoutComponentProps> = ({
    children: Sprite,
}) => (
    <Panel>
        <Sprite />
    </Panel>
)

export const MyComponent: React.FC = () => (
    <SuspenseComponent
        repository={repository}
        repositoryArguments={[SpriteType.Sun]}
        layoutComponent={LayoutComponent}
        loadingFallback={<div>loading</div>}
    />
)

Suspend

This is a wrapper similar to redux connect that allows you to use suspense with existing components.

This requires React 16.6+

import { suspend } from 'suspense-utils';

const MyComponentBase: React.FC = () => <div>Hi</div>;

export const MyComponent = suspend(MyComponentBase, {
    loadingFallback: <div>loading</div>
})

Error

Error helpers

Error Boundary

A simple error boundary wrapper.

This requires React 16.6+

import { ErrorBoundary, ErrorBoundaryFallbackProps } from 'suspense-utils';
import { App } from '../';

/* Will show on error state */
const FallbackView: React.FC<ErrorBoundaryFallbackProps> = ({
    error,
    retry
}) => (
    <div>
        <h4>Oh no!</h4>
        <h5>Something went wrong</h5>
        <button onClick={retry}>Click to retry</button>
    </div>
)

export const MyComponent: React.FC = () => (
    <ErrorBoundary fallback={FallbackView}>
        <App />
    </ErrorBoundary>
)

Alternatively you can set the component to retry failure, every 3 seconds stopping after 5 attempts in the below example.

import { ErrorBoundary, ErrorBoundaryFallbackProps } from 'suspense-utils';
import { App } from '../';

/* Will show on error state */
const FallbackView: React.FC = () => (
    <div>
        <h4>Oh no!</h4>
        <h5>Something went wrong</h5>
    </div>
)

export const MyComponent: React.FC = () => (
    <ErrorBoundary
        fallback={FallbackView}
        retryPolicy={{
            times: 5,
            intervalMs: 3000
        }}
    >
        <App />
    </ErrorBoundary>
)

useCallback

This hook matches the api of reacts useCallback however unlike react it pipes errors to the error boundary.
Only use this if your application does not handle the possible error state of things like event handlers, data fetching etc..

This requires React 16.6+

import { useCallack } from 'suspense-utils';

export const Component: React.FC = () => {
    const onClick = useCallack(() => {
        throw new Error('Event handler error');
    }, []);

    return <button onClick={onClick}>Click me </button>
}

Readme

Keywords

none

Package Sidebar

Install

npm i suspense-utils

Weekly Downloads

54

Version

1.1.0

License

MIT

Unpacked Size

608 kB

Total Files

85

Last publish

Collaborators

  • tyson-skiba