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-use-async-callback

v2.1.2

Published

React hook that provides a standard way generate async calls by returning a wrapped callback, a executing and success flags and any error result.

Downloads

275

Readme

react-use-async-callback

React hook that provides a standard way to generate async callbacks by returning an array containing:

  1. a wrapped callback function
  2. a status object including: i. An executing flag ii. an error result created from any raised exceptions iii. an success flag that can be used if success is not otherwise indicated (often ignored and not captured from the returned values).

Any unwanted parts of the return can be ignored via descronstruction.

Installation

Install react-use-async-callback locally within your project folder, like so:

npm install react-use-async-callback

Or with yarn:

yarn add react-use-async-callback

Usage

An example:

import { useAsyncCallback } from 'react-use-async-callback';

const [load, { isExecuting: isLoading, errors: loadingErrors, successfullyExecuted: loadingSuccess }] = useAsyncCallback(async () : Promise<any> => {
	// Perform your async task here.
}, []);

In this example:

  • load is a wrapped version of the passed in callback that manages isLoading and loadingErrors for you.
  • isLoading is a boolean stored in the react state set to true when the callback is executing and false when the callback execution has finished.
  • loadingErrors is a string stored in the react state containing any raised exception during execution of the callback. It is cleared (set to an empty string) if execution completes with no errors.
  • loadingSuccess is a boolean that is true when the task completed successfully.

Often the success of a task is handled by the task itself, so the success flag can be omitted from the returned values:

const [save, { isExecuting: isSaving, errors: savingErrors }] = useAsyncCallback(async () : Promise<any> => {
	// Perform your async task here.
}, []);

Or if you are also handling errors elsewhere:

const [save, { isExecuting: isSaving }] = useAsyncCallback(async () : Promise<any> => {
	// Perform your async task here.
}, []);

API reference

/**
 * React hook that provides a standard way to generate async callbacks by returning an array containing:
 *  1. a wrapped callback function
 *  2. a status object including:
 *      i. An executing flag
 *      ii. an error result created from any raised exceptions
 *      iii. an success flag that can be used if success is not otherwise indicated (often ignored and not captured from the returned values).
 * 
 * @param callback Async callback that will be wrapped with the extended functionality and returned.
 * @param deps Dependencies passed to React's useCallback()
 */
export function useAsyncCallback<T extends (...args: any[]) => Promise<any>>(callback: T, deps: React.DependencyList): [T, AsyncCallbackStatus]

/**
 * Class containing the status of a useAsyncCallback() action.
 * 
 * This class replaces the three optional array arguments from useAsyncCallback() with a single class, which will make extending
 * the reported status easier in the future, and matches the way status is returned from other hook libraries a bit more closely now
 * there are more hook libraries around.
 */
export interface AsyncCallbackStatus {
    /**
     * True while the async action is being executed.
     */
    isExecuting: boolean,

    /**
     * Errors raised by the callback.
     */
    errors: any,

    /**
     * Flag set to true if the last invocation of the scallback executed successfully (i.e. without throwing any exceptions).
     */
    successfullyExecuted: boolean,
}

Upgrading form previous versions

The object returned in the array from useAsyncCallback() changed in version 2.0.0 creating a breaking API change. The decision was made for version 2.0.0 to combine the options representing status into a single object, returned as the second part of the array, rather than returning each seperatly in the array. This gives the caller more flexiblity on which items to use or ignore, as well as a option to keep all this state in a single object where that is useful (for example when lots of callbacks are being used).

To update from version 1.x you will need to change the syntax of consuming the result to take into account the status object being returned. This simply requires the use of the object desconstruction syntax rather than the array deconstruction syntax. e.g.:

import { useAsyncCallback } from 'react-use-async-callback';

// Old style (react-use-async-callback 1.x)
const [load, isLoading, loadingErrors, loadingSuccess] = useAsyncCallback(async () : Promise<any> => {
	// Perform your async task here.
}, []);

// In the new style (react-use-async-callback 2.x) becomes
const [load, { isExecuting: isLoading, errors: loadingErrors, successfullyExecuted: loadingSuccess }] = useAsyncCallback(async () : Promise<any> => {
	// Perform your async task here.
}, []);

License

Licensed under the MIT license.