Giter Club home page Giter Club logo

use-async-function's Introduction

useAsyncFunction Tweet version minzipped size downloads build

useAsyncFunction is a React hook that integrates an asynchronous function's state with a React function component's state. This automates the process of re-rendering the React function component as the asynchronous function's state changes between pending, resolved, and rejected.

Install

  • npm i use-async-function or
  • yarn add use-async-function

Use

import useAsyncFunction, { State } from 'use-async-function';

const myAsyncFunction = async (): Promise<void> => {
  await one();
  await two();
  return 'three';
};

function MyComponent() {
  const dispatch = useAsyncFunction(myAsyncFunction);

  if (!dispatch.state) {
    dispatch();
  }

  if (dispatch.state === State.Fulfilled) {
    return <div>The response was {dispatch.value}.</div>;
  }

  if (dispatch.state === State.Rejected) {
    return <div>An error occurred: {dispatch.error}</div>;
  }

  // Pending and uninitiated.
  return <Loading />;
}

Parameters

useAsyncFunction(Function)

The first parameter of the useAsyncFunction hook is the asynchronous function itself.

useAsyncFunction(Function, Options)

If you are not using an identity reducer, the second parameter of the useAsyncFunction hook is the options object.

useAsyncFunction(Function, Reducer)

If you are using an identity reducer, the second parameter of the useAsyncFunction hook is the identity reducer.

useAsyncFunction(Function, Reducer, Options)

If you are using both an identity reducer and an options object, the identity reducer is the second parameter of the useAsyncFunction hook, and the options object is the third parameter of the useAsyncFunction hook.

Identity Reducer

An identity reducer allows you to track multiple calls to the same asynchronous function. This is particularly useful when tracking API calls, where each call's fulfillment, pending, and rejection states are unique.

An identity reducer takes the call's arguments as its arguments and returns a string unique to that call.

// Asynchronously fetch a user's data by their username.
function fetchUser({ username }) {
  return fetch(`/users/${username}`);
}

// Uniquely identify an asynchronous function call by the username.
function idByUsername({ username }) {
  return username;
}

function MyComponent() {
  const dispatch = useAsyncFunction(fetchUser, idByUsername);

  // We can determine if this call has been made by the presence of a property
  //   with the call's ID.
  if (!dispatch.admin) {
    dispatch({ username: 'admin' });
    return null;
  }
  if (!dispatch.bob) {
    dispatch({ username: 'bob' });
    return null;
  }

  // The state of the call is stored on the property with the call's ID.
  if (dispatch.admin.state === State.Fulfilled) {
    return <div>Admin loaded with {dispatch.admin.value}.</div>;
  }
}

Options

throwError

Default: false

Type: boolean

If true, the asynchronous function will throw any encountered errors, requiring a .catch block.

If false, the asynchronous function will swallow any errors. The component will rerender, and the error property of the async function will be set to the caught error.

Sponsor ๐Ÿ’—

If you are a fan of this project, you may become a sponsor via GitHub's Sponsors Program.

use-async-function's People

Contributors

dependabot[bot] avatar quisido avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

linecode

use-async-function's Issues

Feature Req: add dependency array similar to useMemo

Proposed Syntax:
const loadUsers = useAsyncFunction( () => fetch('/users'), [x,y,z]);

where the array of [x,y,z] is used, either directly with useMemo, or indirectly with the same basic behavior, to reset the Fulfilled state and force the function to be called again.

My use case is that the user can change the server, negating all cached values, but my wrapping API hides that detail so the async hook would probably not notice that it happened and remain Fulfilled.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.