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

react-async-hooks

v1.0.4

Published

React hooks for async tasks

Downloads

46

Readme

React hooks for async tasks

There are two hooks, useAsync and useAsyncCallback. useAsync is like useEffect. It will run when dependencies change. useAsyncCallback is like useCallback. It returns a function. Both hooks support aborting using an AbortSignal.

useAsync

Basic

import { useAsync } from 'react-async-hooks';

const fetchMessage = async id => {
    // Fetch data using id
};

const Message = props => {
    const { state, error, value } = useAsync(() => fetchMessage(props.id), [props.id]);
    return <div>{/* ... */}</div>;
};

fetchMessage will be called when props.id changes. state will be 'unknown', 'error' or 'done'. If state is not 'done' then value will be undefined. If state is not 'error' then error will be undefined.

Aborting

import { useAsync } from 'react-async-hooks';

const fetchMessage = async (id, signal) => {
    // Fetch data using id
    // Cancel fetch using signal and throw error
};

const Message = props => {
    const { state, error, value } = useAsync(signal => fetchMessage(props.id, signal), [props.id]);
    return <div>{/* ... */}</div>;
};

Any error thrown by fetchMessage after aborting will be caught. signal is an AbortSignal.

useAsyncCallback

import { useState } from 'react';
import { useAsyncCallback } from 'react-async-hooks';

const fetchMessage = async (id, signal) => {
    // Fetch data using id
    // Cancel fetch using signal and throw error
};

const Message = props => {
    const [message, setMessage] = useState();

    const updateMessage = useAsyncCallback(
        async signal => {
            try {
                const message = await fetchMessage(props.id, signal);
                setMessage(message);
            } catch (error) {
                if (!signal.aborted) {
                    throw error;
                }
            }
        },
        [props.id, setMessage],
    );

    return (
        <div>
            <button onClick={updateMessage}>Update message</button>
            <div>{/* ... */}</div>
        </div>
    );
};

fetchMessage will be called when button is clicked. Any error thrown due to aborting must be handled.

Race conditions

Wrong:

import { useState } from 'react';
import { useAsync } from 'react-async-hooks';

const fetchMessage = async id => {
    // Fetch data using id
};

const Message = props => {
    const [message, setMessage] = useState();

    useAsync(async () => {
        const message = await fetchMessage(props.id);
        setMessage(message);
    }, [props.id]);

    return <div>{/* ... */}</div>;
};

Here it's possible that an old fetchMessage call resolves after a new fetchMessage call. This is handled automatically in the value returned by useAsync but if state is changed inside the callback passed to useAsync or useAsyncCallback then signal.aborted should be checked before changing state.

Correct:

import { useState } from 'react';
import { useAsync } from 'react-async-hooks';

const fetchMessage = async id => {
    // Fetch data using id
};

const Message = props => {
    const [message, setMessage] = useState();

    useAsync(
        async signal => {
            const message = await fetchMessage(props.id);
            if (!signal.aborted) {
                setMessage(message);
            }
        },
        [props.id],
    );

    return <div>{/* ... */}</div>;
};

API

useAsync<T>(callback, deps) => result

  • callback: (signal: AbortSignal) => PromiseLike<T>

  • deps: Array

  • result: Object

  • result.state: 'unknown' | 'error' | 'done'

  • result.error: any | undefined

  • result.value: T | undefined

  • PromiseLike can be any Promises/A+ compliant promise.

useAsyncCallback<T, U>(callback, deps) => result

  • callback: (signal: AbortSignal, ...args: T) => U

  • deps: Array

  • result: (...args: T) => U

ESLint

Use additionalHooks option of eslint-plugin-react-hooks to check for incorrect dependencies.

{
    "rules": {
        "react-hooks/exhaustive-deps": [
            "error",
            {
                "additionalHooks": "(useAsync|useAsyncCallback)"
            }
        ]
    }
}