Need help with use-async-effect?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

rauldeheer
229 Stars 11 Forks MIT License 58 Commits 5 Opened issues

Description

:running: Asynchronous side effects, without the nonsense

Services available

!
?

Need anything else?

Contributors list

Logo npm version license


:running: Asynchronous side effects, without the nonsense.

useAsyncEffect(async () => {
  await doSomethingAsync();
});

Installation

npm install use-async-effect

or

yarn add use-async-effect

This package ships with TypeScript and Flow types.

API

The API is the same as React's

useEffect()
, except for some notable differences:
  • The destroy function is passed as an optional second argument:
useAsyncEffect(callback, dependencies?);
useAsyncEffect(callback, onDestroy, dependencies?);
  • The async callback will receive a single function to check whether the component is still mounted:
useAsyncEffect(async isMounted => {
  const data1 = await fn1();
  if (!isMounted()) return;

const data2 = await fn2(); if (!isMounted()) return;

doSomething(data1, data2); });

Examples

Basic mount/unmount

javascript
useAsyncEffect(async () => console.log('mount'), () => console.log('unmount'), []);

Omitting destroy

javascript
useAsyncEffect(async () => console.log('mount'), []);

Handle effect result in destroy

javascript
useAsyncEffect(() => fetch('url'), (result) => console.log(result));

Making sure it's still mounted before updating component state

javascript
useAsyncEffect(async isMounted => {
  const data = await fetch(`/users/${id}`).then(res => res.json());
  if (!isMounted()) return;
  setUser(data);
}, [id]);

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.