Skip to content

lekhasy/use-promise-result

Repository files navigation

Tired creating these state in your component: loading, error, data, retry?
Also you need to check if component unmounted, is the current response still valid ...
With use-promise-result, your job is to specify how to get data, we take care all the boring flags.

Build Status:

npm publish

Install:

npm i use-promise-result

Usage:

import { usePromiseTracker } from "use-promise-result";

const dataProvider = async () => {
  return (await axios.get("https://jsonplaceholder.typicode.com/todos/1")).data;
};

function App() {
  const { data, error, loading, success, track, tracking } = usePromiseTracker(
    dataProvider()
  );

  const handleReload = () => track(dataProvider());

  // ...
}

Fetch data on click:

const { data, error, loading, success, track, tracking } = usePromiseTracker();

const handleReload = () => track(dataProvider());

API Reference:

usePromiseTracker

usePromiseTracker() : {data, error, loading, success, track, tracking}

Returned value

- data: value returned from the promise
- error: error throw from the promise
- loading: indicate state of the promise
- track: call this function to track another promise
- tracking: indicate that the hook is tracking a promise
- success: tracking && !state.loading && !state.error

Demo:

https://stackblitz.com/edit/react-kuzhwn?file=package.json