Mook5ter
Mook5ter

Reputation: 233

Handling errors within custom SWR hook

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 };
}

Upvotes: 8

Views: 11226

Answers (1)

juliomalves
juliomalves

Reputation: 50318

From SWR Error Handling documentation:

If an error is thrown inside fetcher, it will be returned as error by the hook.

In your case, you can simply handle to 400 status code response in the fetcher and throw an error after the handling is done.

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'
            }
        });

        if (res.statusCode === 400) {
            // Add your custom handling here

            throw new Error('A 400 error occurred while fetching the data.'); // Throw the error
        }

        return res.json();
    }
);

Upvotes: 6

Related Questions