프롤로그 근로 이번 미션은 fetch를 axios로 변환하는 것이었다.
그 과정에서 axios에 header가 반복되는 것이 보였고, 이를 util로 분리하기로 했다.
axios.create를 통해 headers를 정의하고, accessToken이 있냐 없느냐에 따라 'Authorization'을 추가해 주었다.
import axios from 'axios';
import { BASE_URL } from '../configs/environment';
interface AxiosInstanceProps {
accessToken?: string;
}
export const createAxiosInstance = ({ accessToken }: AxiosInstanceProps) => {
const headers = {
'Content-Type': 'application/json; charset=UTF-8',
};
if (accessToken) {
headers['Authorization'] = `Bearer ${accessToken}`;
}
return axios.create({
baseURL: BASE_URL,
headers: accessToken ? headers : {},
});
};
위 util 함수를 이용해 axios를 사용하는 부분을 다 수정해 주었다.
(accessToken이 있는 경우)
export const requestGetStudylog = ({ id, accessToken }) =>
{
const instance = createAxiosInstance({ accessToken });
return instance.get(`/studylogs/${id}`);
}
(accessToken이 없는 경우)
export const requestGetFilters = () => {
const instance = createAxiosInstance()
return instance.get('/filters')
}
그런데, 매 함수마다
'const instance = createAxiosInstance({ accessToken })'이나
'const instance = createAxiosInstance()'이 반복되는 모습을 볼 수 있었다.
그래서 반복되는 부분을 가장 바깥 부분에 선언하였다.
const instanceWithoutToken = createAxiosInstance();
const instanceWithToken = (accessToken) => createAxiosInstance({ accessToken });
export const requestGetStudylog = ({ id, accessToken }) =>
instanceWithToken(accessToken).get(`/studylogs/${id}`);
export const requestGetFilters = () => instanceWithoutToken.get('/filters');
그런데 type error가 났다.
'const instance = createAxiosInstance()'를 선언만 해도 에러가 난다.
'const instance = createAxiosInstance({ accessToken })'는 괜찮은데
'const instance = createAxiosInstance()' 즉, accessToken이 없는 경우는 에러가 나는 이유는 뭘까?
바로 AxiosInstanceProps이 없을 때의 기본값을 설정해주지 않아서이다.
객체를 구조 분해 할당하려고 했으나 해당 객체가 undefined가 떴고 여기서 accessToken을 추출하려고 했기 때문에 발생한 것이다.
이 에러는 기본값을 주면 해결된다.
import axios from 'axios';
import { BASE_URL } from '../configs/environment';
interface AxiosInstanceProps {
accessToken?: string;
}
export const createAxiosInstance = ({ accessToken }: AxiosInstanceProps = {}) => {
const headers = {
'Content-Type': 'application/json; charset=UTF-8',
};
if (accessToken) {
headers['Authorization'] = `Bearer ${accessToken}`;
}
return axios.create({
baseURL: BASE_URL,
headers: accessToken ? headers : {},
});
};
AxiosInstanceProps의 기본값을 {}으로 주면 에러 해결!
'ERROR' 카테고리의 다른 글
nvm: command not found (0) | 2023.09.08 |
---|---|
Module not found: Error: Can't resolve 'react-dom/client' in '경로' (0) | 2022.06.05 |
댓글