Skip to content

Instantly share code, notes, and snippets.

@juanpablocs
Created May 20, 2022 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanpablocs/b760c4ac23741f2f9ecfa89fc44c6775 to your computer and use it in GitHub Desktop.
Save juanpablocs/b760c4ac23741f2f9ecfa89fc44c6775 to your computer and use it in GitHub Desktop.
useAxios with global error boundaries

hook axios sugar

import { useEffect, useRef } from 'react';
import axios, { AxiosError, AxiosRequestConfig } from 'axios';
import _useAxios, { configure } from 'axios-hooks';
import { useErrorHandler } from 'react-error-boundary';
import { useToast } from '@chakra-ui/react';

import { API_URL } from '../config';

export const useAxios = (args: AxiosRequestConfig<any>) => {
  const toast = useToast();
  const handleError = useErrorHandler();
  const token =
    typeof window !== "undefined" && window.localStorage.getItem("access_token");

  const instanceRef = useRef(axios.create({
    baseURL: API_URL, headers: {
      Authorization: `Bearer ${token}`,
    }
  }));
  const retryRef = useRef(false);

  useEffect(() => {
    instanceRef.current.interceptors.request.use(
      (config) => {
        const token = localStorage.getItem("token");
        if (token) {
          config.headers = { authorization: `Bearer ${token}` };
        }
        return config;
      },
      (error) => Promise.reject(error)
    );

    instanceRef.current.interceptors.response.use(
      (response) => {
        console.log('interceptor response')
        return response;
      },
      (err: AxiosError) => {
        console.log('err interceptor', err);
        if (err.code === 'ERR_NETWORK') {
          handleError(new Error('Internal error network'))
        }
        if (err.response?.status) {
          toast({ description: err.message })
          if (err.response.status === 401 && !retryRef.current) {
            retryRef.current = true;
            // localStorage.setItem("token", await refreshAccessToken());

            return instanceRef.current(err.config);
          }
        }
        return Promise.reject(err);
      }
    );

    configure({ axios: instanceRef.current });
  }, [handleError, toast]);

  return _useAxios({ ...args });

};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment