
Security News
Crates.io Implements Trusted Publishing Support
Crates.io adds Trusted Publishing support, enabling secure GitHub Actions-based crate releases without long-lived API tokens.
react-async-hook
Advanced tools
const StarwarsHero = ({ id }) => {
const asyncHero = useAsync(fetchStarwarsHero, [id]);
return (
<div>
{asyncHero.loading && <div>Loading</div>}
{asyncHero.error && <div>Error: {asyncHero.error.message}</div>}
{asyncHero.result && (
<div>
<div>Success!</div>
<div>Name: {asyncHero.result.name}</div>
</div>
)}
</div>
);
};
And the typesafe async function could be:
type StarwarsHero = {
id: string;
name: string;
};
const fetchStarwarsHero = async (id: string): Promise<StarwarsHero> => {
const result = await fetch(`https://swapi.co/api/people/${id}/`);
if (result.status !== 200) {
throw new Error('bad status = ' + result.status);
}
return result.json();
};
Examples are running on this page and implemented here (in Typescript)
yarn add react-async-hook
or
npm install react-async-hook --save
This library does not yet support React Suspense, but hopefully it will as soon as it can.
It is possible to debounce a promise.
I recommend awesome-debounce-promise, as it handles nicely potential concurrency issues and have React in mind (particularly the common usecase of a debounced search input/autocomplete)
As debounced functions are stateful, we have to "store" the debounced function inside a component. We'll use for that use-constant (backed by useRef
).
const StarwarsHero = ({ id }) => {
// Create a constant debounced function (created only once per component instance)
const debouncedFetchStarwarsHero = useConstant(() =>
AwesomeDebouncePromise(fetchStarwarsHero, 1000)
);
// Simply use it with useAsync
const asyncHero = useAsync(debouncedFetchStarwarsHero, [id]);
return <div>...</div>;
};
This is one of the most common usecase for fetching data + debouncing in a component, and can be implemented easily by composing different libraries. All this logic can easily be extracted into a single hook that you can reuse. Here is an example:
const searchStarwarsHero = async (
text: string,
abortSignal?: AbortSignal
): Promise<StarwarsHero[]> => {
const result = await fetch(
`https://swapi.co/api/people/?search=${encodeURIComponent(text)}`,
{
signal: abortSignal,
}
);
if (result.status !== 200) {
throw new Error('bad status = ' + result.status);
}
const json = await result.json();
return json.results;
};
const useSearchStarwarsHero = () => {
// Handle the input text state
const [inputText, setInputText] = useState('');
// Debounce the original search async function
const debouncedSearchStarwarsHero = useConstant(() =>
AwesomeDebouncePromise(searchStarwarsHero, 300)
);
const search = useAsyncAbortable(
async (abortSignal, text) => {
// If the input is empty, return nothing immediately (without the debouncing delay!)
if (text.length === 0) {
return [];
}
// Else we use the debounced api
else {
return debouncedSearchStarwarsHero(text, abortSignal);
}
},
// Ensure a new request is made everytime the text changes (even if it's debounced)
[inputText]
);
// Return everything needed for the hook consumer
return {
inputText,
setInputText,
search,
};
};
And then you can use your hook easily:
const SearchStarwarsHeroExample = () => {
const { inputText, setInputText, search } = useSearchStarwarsHero();
return (
<div>
<input value={inputText} onChange={e => setInputText(e.target.value)} />
<div>
{search.loading && <div>...</div>}
{search.error && <div>Error: {search.error.message}</div>}
{search.result && (
<div>
<div>Results: {search.result.length}</div>
<ul>
{search.result.map(hero => (
<li key={hero.name}>{hero.name}</li>
))}
</ul>
</div>
)}
</div>
</div>
);
};
You can use the useAsyncAbortable
alternative. The async function provided will receive (abortSignal, ...params)
.
The library will take care of triggering the abort signal whenever a new async call is made so that only the last request is not cancelled. It is your responsability to wire the abort signal appropriately.
const StarwarsHero = ({ id }) => {
const asyncHero = useAsyncAbortable(
async (abortSignal, id) => {
const result = await fetch(`https://swapi.co/api/people/${id}/`, {
signal: abortSignal,
});
if (result.status !== 200) {
throw new Error('bad status = ' + result.status);
}
return result.json();
},
[id]
);
return <div>...</div>;
};
It can be annoying to have the previous async call result be "erased" everytime a new call is triggered (default strategy). If you are implementing some kind of search/autocomplete dropdown, it means a spinner will appear everytime the user types a new char, giving a bad UX effect. It is possible to provide your own "merge" strategies. The following will ensure that on new calls, the previous result is kept until the new call result is received
const StarwarsHero = ({ id }) => {
const asyncHero = useAsync(fetchStarwarsHero, [id], {
setLoading: state => ({ ...state, loading: true }),
});
return <div>...</div>;
};
If your params are not changing, yet you need to refresh the data, you can call execute()
const StarwarsHero = ({ id }) => {
const asyncHero = useAsync(fetchStarwarsHero, [id]);
return <div onClick={() => asyncHero.execute()}>...</div>;
};
Use a lib that simply adds retry feature to async/promises directly. Doesn't exist? Build it.
MIT
Looking for a React/ReactNative freelance expert with more than 5 years production experience? Contact me from my website or with Twitter.
FAQs
Async hook
The npm package react-async-hook receives a total of 100,452 weekly downloads. As such, react-async-hook popularity was classified as popular.
We found that react-async-hook demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Crates.io adds Trusted Publishing support, enabling secure GitHub Actions-based crate releases without long-lived API tokens.
Research
/Security News
Undocumented protestware found in 28 npm packages disrupts UI for Russian-language users visiting Russian and Belarusian domains.
Research
/Security News
North Korean threat actors deploy 67 malicious npm packages using the newly discovered XORIndex malware loader.