Skip to content

React hook for handle promise data, error and loading states.

License

Notifications You must be signed in to change notification settings

gersondinis/use-promise

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@grd/usePromise()

Simple react hook to handle promises

Note: It works with any Promise implementation, but this documentation uses axios for demonstration.

Dependency: react@>16.8.0

Get started:

Install

yarn add @grd/use-promise;

Import

import usePromise from '@grd/use-promise';

Use

const [invokeFn, {result, error, isLoading}] = usePromise((arg) => Promise(arg))

Example A - invoked on demand:

import { usePromise } from '@grd/use-promise';


export const ExampleA = () => {
  
  const [getUser, {result, error, isLoading}] = usePromise(userId => axios.get(`/users/${userId}`));
  
  return (
    <>
      <button onClick={() => getUser(1)}>Retrieve User</button>
      {result && <p>Hello {result.data?.user?.name}</p>}
      {error && <p>Whoops: {error.message}!</p>}
      {isLoading && <p>loading...</p>}
    </>
  );
};

Example B - invoked on load:

import { usePromise } from '@grd/use-promise';
import { useEffect } from 'react';


export const ExampleB = () => {
  
  const [getUser, {result, error, isLoading}] = usePromise(userId => axios.get(`/users/${userId}`));

  useEffect(() => {
    getUser(1);
  }, [getUser]);
  
  return (
    <>
      {result && <p>Hello {result.data?.user?.name}</p>}
      {error && <p>Whoops: {error.message}!</p>}
      {isLoading && <p>loading...</p>}
    </>
  );
};

About

React hook for handle promise data, error and loading states.

Resources

License

Stars

Watchers

Forks

Packages

No packages published