@isumix/react-suspendable
TypeScript icon, indicating that this package has built-in type declarations

1.0.1 • Public • Published

react-suspendable

Integrates asynchronous code (Promise) within React's Suspense and Error Boundaries

Not experimental. Available since React 16.6. Works with React Native.

Description

Suppose we want to use a Promise in our <CustomComponent>

<Exception fallback="Rejected">
  <Suspense fallback="Pending">
    <CustomComponent /> has asynchronous code and could throw exceptions
  </Suspense>
</Exception>

A Promise has three distinct states:

  • PENDING - will render "Pending" by <Suspense>
  • REJECTED - will render "Rejected" by <Exception>, which is an Error Boundary implementation
  • FULFILLED - will finally render our <CustomComponent>

Install

npm install --save @isumix/react-suspendable
yarn add @isumix/react-suspendable

Example

Play with web example in codesandbox.io

Play with native example in snack.expo.io

import React, { Suspense } from "react";
import { makeSuspendableHook } from "@isumix/react-suspendable";

const promise = new Promise<string>(resolve => {
  setTimeout(() => resolve("DELAYED"), 5000);
});

const useDelayedValue = makeSuspendableHook(promise);

const CustomComponent = () => {
  const val = useDelayedValue();
  return (
    <p>
      This component has a <b>{val}</b> value.
    </p>
  );
};

export default () => (
  <Suspense fallback={<i>Waiting...</i>}>
    <CustomComponent />
  </Suspense>
);

makeSuspendableHook

Create a new Hook from a Promise and return it

const useDelayedValue = makeSuspendableHook(promise);

This is all you going to need

For library writers

makeSuspendable

Create a new suspendable object from a Promise and return it

const suspendable = makeSuspendable(promise);

useSuspendable

Hook that uses suspendable object and returns FULFILLED value or throws an exception

const val = useSuspendable(suspendable);

Dependencies (0)

    Dev Dependencies (1)

    Package Sidebar

    Install

    npm i @isumix/react-suspendable

    Weekly Downloads

    2

    Version

    1.0.1

    License

    ISC

    Unpacked Size

    5.32 kB

    Total Files

    5

    Last publish

    Collaborators

    • isumix