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.
npm i use-promise-result
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());
// ...
}
const { data, error, loading, success, track, tracking } = usePromiseTracker();
const handleReload = () => track(dataProvider());
usePromiseTracker() : {data, error, loading, success, track, tracking}
- 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