I am trying to create a reusable custom hook (useRequest) where I can fetch data with axios, display it and have a loading state. In case of an error I want it to be caught by useRequest. I'm having trouble catching eventual errors and passing the axios request to useRequest. Currently I'm only getting null for the error message.
EDIT: I use generated api which uses axios. So to make my fetch request it would look something like this:
import {GeneratedApi} from '/generatedApi'
const generatedApi = new GeneratedApi(configuration) //configuration is for editing the headers etc.
const response = await generatedApi.getData();
setData(response.data);
My code:
import axios, { AxiosResponse } from "axios";
import { useEffect, useState } from "react";
const useRequest = (promise: Promise<AxiosResponse<any>>) => {
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchData = async () => {
try {
setError(null);
await promise;
setLoading(false);
setError(null);
} catch (error) {
setLoading(false);
setError("Error: " + JSON.stringify(error));
}
};
fetchData();
}, [promise]);
return [loading, error];
};
export default function App() {
const [data, setData] = useState<any | null>(null);
const [loading, error] = useRequest(async () => {
const response = await axios.get("https://jsonplaceholder.typicode.com/todos");
setData(response.data);
return response;
});
if (loading) {
return <p>Loading ...</p>;
} else if (data) {
return <p>{data}</p>;
} else {
return <p>Error: {error}</p>;
}
}