React hook to execute and watch async function

react-async-watcher

React hook to execute and watch async function.

This package is made for handle asynchronous tasks, such as backend api calls.

  • execute async function whenever and whatever you want
  • provide execution status and result
  • typescript support
  • super tiny

Quick Start

import { useAsyncWatcher } from 'react-async-watcher';

const GetUsersButton = () => {
  const { execute, reset, status, result, error } = useAsyncWatcher();
  
  return (
    <button
      onClick={() => {
        execute(async () => {
          // fetch remote data
          const data = await getUsersApi();
          
          // you may want to post-process data, use redux dispatch and so on
          
          // if return data, result variable will be filled with the data
          return data;
        })
      }}
    >
      Get User List
    </button>
  );
}

Usage

Inside your React or React-Native project directory, run the following command:

yarn add react-async-watcher

or with npm

npm install react-async-watcher

API

const { execute, reset, status, result, error } = useAsyncWatcher();

useAsyncWatcher

You can pass type to useAsyncWatcher, eq: useAsyncWatcher<number>(), then type of result will be number | undefined

execute

execute(async () => {
  // do whatever you want
  
  // if your need to render some data
  // return it, then result variable will hold the data
})

reset

use it to clear status, result, error

status

"initial" | "loading" | "success" | "failure";

GitHub

https://github.com/xralphack/react-async-watcher