Hooks
A Custom hook for managing this fancy promises inside a component, we wanted to, you'll probably want too.
useAwait
Returns a React readable promise reader, and a resolver function that can overide the promise result.
Follow the docs in this useAwait demo.
Arguments
executor: () => T | Promise
executor: () => T | Promise
A function that returns a value or promise (this function will be passed to the constructor of ReadablePromise
).
configs: { suspend: boolean } = { suspend: false }
(optional)
configs: { suspend: boolean } = { suspend: false }
(optional)An optional object with configuration options. Currently, the only supported option is suspend
, which determines whether the read
method should purposefully suspend it's caller component for undetermined time. The default value for it is false
.
Return
It returns an array with two elements. The first element is the read
method of a ReadablePromise
instance, which gets the value resolved from the executor
function. The second element is a resolver function, that works like a setter by overriding the resolved value of the promise.
Default usage
This example displays the default usage for most useAwait
use cases.
function App() {
const [fetchStuff] = useAwait(()=> {
// asynchronous things you want here...
// return stuff
})
const Loading = () => {
return <p>Loading...</p>;
};
const Content = () => {
const stuff = fetchStuff();
return <p>{stuff.property}</p>;
};
return (
<Suspense fallback={<Loading />}>
<Content />
</Suspense>
);
}
Resolving early and re-setting value with the resolver
In this example the resolver can be used to unsuspend the content early, or work as a setter after they it has rendered once.
function App() {
const [fetchStuff, resolveStuff] = useAwait(()=> {
// asynchronous things you want here...
// return stuff
})
const Loading = () => {
return <p onClick={()=> resolveStuff(newStuff)}>Loading...</p>;
};
const Content = () => {
const stuff = fetchStuff();
return <p onClick={()=> resolveStuff(newStuff)}>{stuff.property}</p>;
};
return (
<Suspense fallback={<Loading />}>
<Content />
</Suspense>
);
}
Using it to intentionally suspend Suspense
children
Suspense
childrenThe suspend option can be passed as true
in order to turn the reader into a function that indefinetly throws back a promise, which suspends the content in Suspense
until you use the resolver to overide the reader return value.
Whitness it on a sandbox.
function App() {
const [suspender, unsuspend] = useAwait(()=> {
// asynchronous things you want here, or not in this case
}, { suspend: true })
const Loading = () => {
return <p onClick={()=> unsuspend()}>Loading...</p>;
};
const Content = () => {
return <p>Why the wait?</p>;
};
return (
<Suspense fallback={<Loading />} cause={suspender}>
<Content />
</Suspense>
);
}
Last updated