React hook for async effects powered by generator functions.
Simple type-safe async effects for React powered by generator functions.
import React from "react"; import useAsyncEffect from "@n1ru4l/use-async-effect";const MyComponent = ({ filter }) => { const [data, setData] = React.useState(null);
useAsyncEffect( function* (onCancel, c) { const controller = new AbortController();
onCancel(() => controller.abort()); const data = yield* c( fetch("/data?filter=" + filter, { signal: controller.signal, }).then((res) => res.json()) ); setData(data); }, [filter]
);
return data ? : null; };
yarn add -E @n1ru4l/use-async-effect
or
npm install -E @n1ru4l/use-async-effect
Doing async stuff with
useEffectclutters your code:
useEffect
This micro library tries to solve this issue by using generator functions:
useAsyncEffect
fetchrequest with
AbortController
import React, { useEffect } from "react";const MyComponent = ({ filter }) => { const [data, setData] = useState(null);
useEffect(() => { let isCanceled = false; const controller = new AbortController();
const runHandler = async () => { try { const data = await fetch("/data?filter=" + filter, { signal: controller.signal, }).then((res) => res.json()); if (isCanceled) { return; } setData(data); } catch (err) {} }; runHandler(); return () => { isCanceled = true; controller.abort(); };
}, [filter]);
return data ? : null; };
import React from "react"; import useAsyncEffect from "@n1ru4l/use-async-effect";const MyComponent = ({ filter }) => { const [data, setData] = useState(null);
useAsyncEffect( function* (onCancel, c) { const controller = new AbortController();
onCancel(() => controller.abort()); const data = yield* c( fetch("/data?filter=" + filter, { signal: controller.signal, }).then((res) => res.json()) ); setData(data); }, [filter]
);
return data ? : null; };
Works like
useEffect, but with a generator function.
import React, { useState } from "react"; import useAsyncEffect from "@n1ru4l/use-async-effect";const MyDoggoImage = () => { const [doggoImageSrc, setDoggoImageSrc] = useState(null); useAsyncEffect(function* (_, c) { const { message } = yield* c( fetch("https://dog.ceo/api/breeds/image/random").then((res) => res.json()) ); setDoggoImageSrc(message); }, []);
return doggoImageSrc ?
: null; };
fetchrequest)
You can react to cancels, that might occur while a promise has not resolved yet, by registering a handler via
onCancel. After an async operation has been processed, the
onCancelhandler is automatically being unset.
import React, { useState } from "react"; import useAsyncEffect from "@n1ru4l/use-async-effect";const MyDoggoImage = () => { const [doggoImageSrc, setDoggoImageSrc] = useState(null); useAsyncEffect(function* (onCancel, c) { const abortController = new AbortController(); onCancel(() => abortController.abort()); const { message } = yield c( fetch("https://dog.ceo/api/breeds/image/random", { signal: abortController.signal, }).then((res) => res.json()) ); setDoggoImageSrc(message); }, []);
return doggoImageSrc ?
: null; };
Similar to
React.useEffectyou can return a cleanup function from your generator function. It will be called once the effect dependencies change or the component is unmounted. Please take note that the whole generator must be executed before the cleanup handler can be invoked. In case you setup event listeners etc. earlier you will also have to clean them up by specifiying a cancel handler.
import React, { useState } from "react"; import useAsyncEffect from "@n1ru4l/use-async-effect";const MyDoggoImage = () => { const [doggoImageSrc, setDoggoImageSrc] = useState(null); useAsyncEffect(function* (_, c) { const { message } = yield* c( fetch("https://dog.ceo/api/breeds/image/random").then((res) => res.json()) ); setDoggoImageSrc(message);
const listener = () => { console.log("I LOVE DOGGIES", message); }; window.addEventListener("mousemove", listener); return () => window.removeEventListener("mousemove", listener);
}, []);
return doggoImageSrc ?
: null; };
eslint-plugin-react-hooks
You need to configure the
react-hooks/exhaustive-depsplugin to treat
useAsyncEffectas a hook with dependencies.
Add the following to your eslint config file:
{ "rules": { "react-hooks/exhaustive-deps": [ "warn", { "additionalHooks": "useAsyncEffect" } ] } }
We expose a helper function for TypeScript that allows interferring the correct Promise resolve type. It uses some type-casting magic under the hood and requires you to use the
yield*keyword instead of the
yieldkeyword.
useAsyncEffect(function* (setErrorHandler, c) { const numericValue = yield* c(Promise.resolve(123)); // type of numericValue is number 🎉 });
useAsyncEffectHook
Runs a effect that includes async operations. The effect ins cancelled upon dependency change/unmount.
function useAsyncEffect( createGenerator: ( setCancelHandler: ( onCancel?: null | (() => void), onCancelError?: null | ((err: Error) => void) ) => void, cast: (promise: Promise) => Generator, T> ) => Iterator, deps: React.DependencyList ): void;
Please check our contribution guides Contributing.
MIT.