npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@n1ru4l/use-async-effect

v1.4.0

Published

[![npm](https://img.shields.io/npm/v/@n1ru4l/use-async-effect.svg)](https://www.npmjs.com/package/@n1ru4l/use-async-effect) [![npm bundle size](https://img.shields.io/bundlephobia/min/@n1ru4l/use-async-effect)](https://bundlephobia.com/result?p=@n1ru4l/us

Downloads

13,061

Readme

useAsyncEffect

npm npm bundle size Dependencies NPM CircleCI semantic-release

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 ? <RenderData data={data} /> : null;
};

Install Instructions

yarn add -E @n1ru4l/use-async-effect

or

npm install -E @n1ru4l/use-async-effect

The problem

Doing async stuff with useEffect clutters your code:

  • 😖 You cannot pass an async function to useEffect
  • 🤢 You cannot cancel an async function
  • 🤮 You have to manually keep track whether you can set state or not

This micro library tries to solve this issue by using generator functions:

  • ✅ Pass a generator to useAsyncEffect
  • ✅ Return cleanup function from generator function
  • ✅ Automatically stop running the generator after the dependency list has changed or the component did unmount
  • ✅ Optional cancelation handling via events e.g. for canceling your fetch request with AbortController

Example

Before 😖

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 ? <RenderData data={data} /> : null;
};

After 🤩

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 ? <RenderData data={data} /> : null;
};

Usage

Works like useEffect, but with a generator function.

Basic Usage

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 ? <img src={doggoImageSrc} /> : null;
};

Edit use-async-effect doggo demo

Cancel handler (Cancelling an in-flight fetch request)

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 onCancel handler 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 ? <img src={doggoImageSrc} /> : null;
};

Edit use-async-effect doggo cancel demo

Cleanup Handler

Similar to React.useEffect you 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 ? <img src={doggoImageSrc} /> : null;
};

Edit use-async-effect cleanup doggo demo

Setup eslint for eslint-plugin-react-hooks

You need to configure the react-hooks/exhaustive-deps plugin to treat useAsyncEffect as a hook with dependencies.

Add the following to your eslint config file:

{
  "rules": {
    "react-hooks/exhaustive-deps": [
      "warn",
      {
        "additionalHooks": "useAsyncEffect"
      }
    ]
  }
}

TypeScript

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 yield keyword.

useAsyncEffect(function* (setErrorHandler, c) {
  const numericValue = yield* c(Promise.resolve(123));
  // type of numericValue is number 🎉
});

API

useAsyncEffect Hook

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: <T>(promise: Promise<T>) => Generator<Promise<T>, T>
  ) => Iterator<any, any, any>,
  deps?: React.DependencyList
): void;

Contributing

Please check our contribution guides Contributing.

LICENSE

MIT.