DocumentationπŸ› οΈ UtilsπŸ› οΈ useApi Hook

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

  1. Create the hook instance by passing the response type to the useApi hook.
const api = useApi<{
  data: {
    name: string;
  };
}>();
  1. Use axios to make the API call and pass the promise to the handle 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"));
  1. 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>;

MIT 2024 Β© Nextra.