I've written a custom hook that uses SWR to retrieve data from my API whilst setting the 'Authentication' header for the request.
The hook is working fine for all successful requests but I want to be able to handle failed requests (400 status codes).
I'm able to access the status code with the result from const res = await fetch(url
but how do I return the error in the error
parameter to the caller of the hook?
import useSWR from 'swr';
export default function useAPI(path) {
const auth = useAuth();
const { data, error, isValidating, mutate } = useSWR(
!path ? null : `${process.env.NEXT_PUBLIC_API_URL}${path}`,
async (url) => {
const res = await fetch(url, {
headers: {
Authorization: `Bearer ${auth.user.token}`,
accept: 'application/json',
},
});
return res.json();
}
);
return { data, error, isValidating, mutate };
}