useApi
The useApi
hook is a custom hook that helps you to fetch data from an API. It helps you handling the loading state, error state, and the data state with type safety.
Usage
- Create the hook instance by passing the response type to the
useApi
hook.
const api = useApi<{
data: {
name: string;
};
}>();
- Use
axios
to make the API call and pass the promise to thehandle
method. It returns a promise that resolves to the data as well as maintaining the loading state, error state, and the data state.
await api.handle(axios.get("/api/users"));
// or await
const response = await api.handle(axios.get("/api/users"));
- You can use the
data
,loading
,error
states in the component.
if (api.loading) return <div>Loading...</div>;
if (api.error) return <div>Error: {api.error.message}</div>;
return <div>{api.data.name}</div>;