Not experimental. Available since React 16.6. Works with React Native.
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>
npm install --save @isumix/react-suspendable
yarn add @isumix/react-suspendable
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>
);
Create a new Hook from a Promise
and return it
const useDelayedValue = makeSuspendableHook(promise);
This is all you going to need
Create a new suspendable
object from a Promise
and return it
const suspendable = makeSuspendable(promise);
Hook that uses suspendable
object and returns FULFILLED value or throw
s an exception
const val = useSuspendable(suspendable);