Tired creating these state in your component: isLoading, isError, data, retry?
With use-promise-result, your job is to specify how to get data, we take care all the boring flags.
npm i use-promise-result
import { usePromiseResult } 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, reload } =
usePromiseResult(dataProvider);
// ...
}
const { data, error, loading, success, reload } =
usePromiseResult(dataProvider, false);
Passing the second parameter to fail would stop usePromiseResult from calling data provider on mount.
Later you can call reload function to trigger the call to data provider (ex: when user click on a button)
- usePromiseResult(<dataProvider>, [initFetch]) : {data, error, loading, success, reload}
- data: value returned from dataProvider
- error: error throw from dataProvider
- loading: indicate state of the promise returned from dataProvider
- reload: call this function to reload data
- reloadCount: number of time dataProvider get involved, use this with initFetch = false
- success: success = !state.loading && !state.error
https://stackblitz.com/edit/react-kuzhwn?file=package.json
Author: lekhasy
The Demo/Documentation: View The Demo/Documentation
Download Link: Download The Source Code
Official Website: https://github.com/lekhasy/use-promise-result
License: MIT
#react #javascript #web-development #programming #developer