@grd/use-promise

1.0.0 • Public • Published

@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>}
    </>
  );
};

Dependencies (0)

    Dev Dependencies (3)

    Package Sidebar

    Install

    npm i @grd/use-promise

    Weekly Downloads

    0

    Version

    1.0.0

    License

    MIT

    Unpacked Size

    5.93 kB

    Total Files

    4

    Last publish

    Collaborators

    • grd