swr + axios interceptor 오류 문제

김종현·2023년 7월 27일
0

문제점

swr에 의한 업데이트시마다 axios interceptor로 인해 오류 지속적으로 발생.

현재 나의 코드

//instance 생성.
const api = axios.create({
    baseURL: process.env.REACT_APP_API_URL,
    headers: {
        Authorization: `Bearer ${accessTokenInLocalStorage}`
    },
    withCredentials: true,
});
//interceptor : 요청시 수행 전에 localStorage에서 토큰 획득.
api.interceptors.request.use(
    config => {
        //요청을 보내기 전에 수행할 로직
        const token = getToken();
        if (token) {
            console.log('요청 인터셉터 - 엑세스 토큰 획득 완료')
        }
        return config;
    },
    error => {
        //요청 에러 발생 시 수행할 로직
        console.log('error', error); //디버깅 로직 예정
        return Promise.reject(error);
    }
);
//swr : axios interceptor에서 얻은 토큰 정보를 토대로 api 요청을 보내서 유저 정보를 받아와 전역적으로 사용.
import useSWR from 'swr'
import api from '../api/axiosInstance';
import { API_USER_ACCESS_TOKEN } from './constant';

const fetcher = (url: string) => api.get(url).then(res => res.data)

export function useUser() {
    const petchingURL = `${process.env.REACT_APP_API_URL}${API_USER_ACCESS_TOKEN}`

    const { data, error, isLoading } = useSWR(petchingURL, fetcher)

    if (isLoading) {
        console.log('로딩중')
    }
    if (error && data === undefined) { // 데이터가 없을 때만 에러 출력
        console.error('Error fetching user data :', error.message);
    }
    if (data) {
        console.log('data 가져옴', data.userData);
        const userData = data.userData;
        return { userData, isError: false };
    }

    return { userData: null, isError: true };

}

문제 판단

axios 인스턴스를 생성했을 때 다른 api에서도 사용하는 인스턴스를 swr 코드에 사용해서 난 것이 아닐까?

const api = axios.create({
    baseURL: process.env.REACT_APP_API_URL,
    headers: {
        Authorization: `Bearer ${accessTokenInLocalStorage}`
    },
    withCredentials: true,
});

바로 이 코드를 swr에서도 공유하기 때문에 업데이트시마다 불필요하게 interceptor가 발동된 것이라고 판단하였다.

문제 해결을 위한 시도

swr에서만 사용하는 전용 인스턴스 생성

//swr 전용 인스턴스 생성
export const swrApi = axios.create({
    baseURL: process.env.REACT_APP_API_URL,
    headers: {
        Authorization: `Bearer ${accessTokenInLocalStorage}`
    },
    withCredentials: true,
});

//swr fetcher를 아래와 같이 변경
const fetcher = (url: string) => swrApi.get(url).then(res => res.data)

결과


콘솔에 에러 없음


네트워크 문제 없음(204 프리플라이트 문제는 다른 글에서 다룰 예정)

결론

swr을 이용해 특정 데이터를 다룰 경우 독립적인 axios instance를 사용해주는 것이 좋다.

profile
나는 나의 섬이다.

1개의 댓글

comment-user-thumbnail
2023년 7월 27일

정보 감사합니다.

답글 달기