react-hook-awaited
v1.1.1
Published
wrapper hook for awaiting promises
Downloads
38
Maintainers
Readme
React useAwaited hook
A helper for working with asynchronous data in react functional components.
See the examples for some use cases.
Install dependency
npm install --save react-hook-awaited
Usage
const useAwaited = require('react-hook-awaited');
const MyComponent = () => {
const apiUrl = 'https://xkcd.com/info.0.json';
const apiResponse = useAwaited((signal) => fetch(apiUrl, { signal }).then((r) => r.json()), [apiUrl]);
switch (apiResponse.state) {
case 'pending':
return (<div>Loading...</div>);
case 'resolved':
return (<div>Latest: {apiResponse.data.num}</div>);
case 'rejected':
return (
<div>
Failed: {apiResponse.error}
<button onClick={apiResponse.forceRefresh()}>Try Again</button>
</div>
);
}
};
If you are using eslint-plugin-react-hooks,
you should configure it to check dependencies for useAwaited
and
useAwaitedWithDefault
:
"react-hooks/exhaustive-deps": ["warn", {
"additionalHooks": "(useAwaited|useAwaitedWithDefault)"
}]
Alternatively, you can provide functions using useCallback
yourself
(this requires more syntax but avoids the need to reconfigure the linter):
const apiResponse = useAwaited(
useCallback(
(signal) => fetch(apiUrl, { signal }).then((r) => r.json()),
[apiUrl]
)
);
API
useAwaited(generatorFunction, deps)
const value = useAwaited(generatorFunction, deps);
Invokes the generatorFunction
and returns the state of the returned
promise.
generatorFunction
: a function which returns a promise which is to be awaited. It is passed a single argument: an AbortSignal which will be marked as aborted if a change means that the current request is no-longer required.deps
: a list of dependencies for thegeneratorFunction
, matching the same API asReact.useCallback
.
The AbortSignal
can be passed directly to fetch
calls to avoid
leaving requests running which are no-longer required:
useAwaited((abortSignal) => fetch('https://example.com', { signal: abortSignal }), []);
note: If the deps
change, the current promise will be discarded,
the AbortSignal
will be triggered, generatorFunction
will be called
again, and the newly returned promise will be awaited.
If you do not provide deps
, the default is to re-invoke the generator
whenever the generator function changes. This means you can pass a
useCallback
-wrapped function instead of providing deps
.
Return value
The response is an object which contains several properties:
state
: one of'pending'
,'resolved'
or'rejected'
. For convenience these are also exported as constantsPENDING
,RESOLVED
,REJECTED
.data
: the current data returned by the promise (ifstate
is'resolved'
, otherwiseundefined
).error
: the current error returned by the promise (ifstate
is'rejected'
, otherwiseundefined
).stats
: an object containing statistics about the current promise:beginTimestamp
: time when the promise began (number of milliseconds since the epoch)endTimestamp
: time when the promise completed (number of milliseconds since the epoch), or undefined ifstate
ispending
.
latestData
: the last successfully resolved data. Unlikedata
, this continues to be available until new data replaces it. This isundefined
until the first request succeeds.latestStats
: an object containing statistics about the last completed promise. Unlikestats
, this continues to be available while new data is loaded. This isundefined
until the first request has completed.forceRefresh
: a function which can be called to force an immediate refresh of the data. This function is guaranteed to be stable (will be the same function instance across all renders).
useAwaitedWithDefault(default, generatorFunction, deps)
Same as useAwaited
, but latestData
will be initialised as
default
rather than undefined
.
Examples
Loading data from a dynamic API endpoint
const useAwaited = require('react-hook-awaited');
const ComicViewer = () => {
const [num, setNum] = useState(1);
const apiUrl = `https://xkcd.com/${num}/info.0.json`;
const apiResponse = useAwaited((signal) => fetch(apiUrl, { signal }).then((r) => r.json()), [apiUrl]);
let content;
if (apiResponse.state === 'pending') {
content = (<div>Loading...</div>);
} else if (apiResponse.state === 'rejected') {
content = (
<div>
Failed to load #{num}: {apiResponse.error}
<br />
<button onClick={apiResponse.forceRefresh()}>Try Again</button>
</div>
);
} else {
content = (
<div>
<h1>{apiResponse.data.title}</h1>
<img src={apiResponse.data.img} alt={apiResponse.data.alt} />
</div>
);
}
return (
<section>
<label>Show XKCD <input type="number" value={num} onChange={setNum} /></label>
{ content }
</section>
);
};
Show latest data with user-controlled refresh
const useAwaited = require('react-hook-awaited');
const DataFetcher = () => {
const apiUrl = 'https://xkcd.com/info.0.json';
const apiResponse = useAwaited((signal) => fetch(apiUrl, { signal }).then((r) => r.json()), [apiUrl]);
let content = null;
if (apiResponse.latestData) {
content = (
<div>
<p>Latest: {apiResponse.latestData.num}</p>
<p>(as of ${new Date(apiResponse.latestStats.endTimestamp).toString()})</p>
</div>
);
}
return (
<section>
{content}
{apiResponse.state === 'pending' ? (
<p>Refreshing...</p>
) : (
<button onClick={apiResponse.forceRefresh()}>Refresh</button>
)}
{apiResponse.state === 'rejected' ? (
<p>Failed to refresh: ${apiResponse.error}</p>
) : null}
</section>
);
};
Automatically refreshing on an interval
This also uses react-hook-final-countdown
const useAwaited = require('react-hook-awaited');
const {useTimeInterval} = require('react-hook-final-countdown');
const DataFetcher = () => {
const apiUrl = 'https://xkcd.com/info.0.json';
const time = useTimeInterval(1000 * 60 * 60); // update every hour
const apiResponse = useAwaited((signal) => fetch(apiUrl, { signal }).then((r) => r.json()), [apiUrl, time]);
return (
<section>
<p>Latest: {apiResponse.latestData?.num}</p>
<p>(as of ${new Date(apiResponse.latestStats?.endTimestamp).toString()})</p>
</section>
);
};