@richard-wang-tw/use-task
v1.0.2
Published
This is a customized react hook that makes it easy to combine task(lazy promise) with react suspense
Downloads
1
Readme
Introduction
With useTask
, you can combine task
with react <Suspense>
What is Task
?
type Task = <A>() => Promise<A>;
Task<A>
represents an asynchronous computation that yields a value of typeA
and never fails.
What is <Suspense>
?
<Suspense>
lets you display a fallback until its children have finished loading.
Getting Started
useTask
Create a task
const getTitle = () => new Promise<string>((rs) => rs("Hello"));
const Title = () => {
return <h1>title</h1>;
};
Add useTask hook in the component
import { useTask } from "@richard-wang-tw/use-task";
const Title = () => {
// the first argument is task
// the second is unique id of the task
const title = useTask(getTitle, "getTitle");
return <h1>{title}</h1>;
};
Wrap the component with <suspense>
const TitleLoader = () => (
<Suspense fallback={<h1>Loading</h1>}>
<Title />
</Suspense>
);
deleteTaskCache
You can use deleteTaskCache("getTitle")
on timeout or triggered by user interaction.
This feature allow you to reload data on next render.