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
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 throw
s an exception
const val = useSuspendable(suspendable);