React에서 Axios 인터셉터로 API 요청/응답 관리하기

MNIII
5 min readSep 21, 2023

--

React와 Axios를 함께 사용하면서 API 호출을 최적화하기 위해 인터셉터를 활용해 보자.

Axios 인터셉터란?

Axios는 JavaScript에서 HTTP 요청을 보내기 위한 라이브러리 이다. Axios의 유용한 기능 중 하나로 인터셉터가 있다.
인터셉터를 사용하면 요청이나 응답을 가로채서 원하는 로직을 수행할 수 있다. 예를 들면, 모든 요청에 토큰을 추가하거나, 응답 로깅, 오류 처리 등을 할 수 있다.

useAxiosInterceptor 커스텀 훅

React에서 커스텀 훅을 통해 반복되는 로직을 효율적으로 재사용 할 수 있다. Axios 인터셉터를 간편하게 설정하고 관리하기 위한 커스텀 훅을 만들면 다음과 같이 구성할 수 있겠다.

const useAxiosInterceptor = (instance) => {

const handleRequest = (config) => {
// ... logic for handling requests
return config;
};

const handleResponse = (response) => {
// ... logic for handling responses
return response;
};

const handleError = (error) => {
// ... logic for handling errors
return Promise.reject(error);
};

// Set up interceptors
const setupInterceptors = () => {
const requestInterceptor = instance.interceptors.request.use(handleRequest, handleError);
const responseInterceptor = instance.interceptors.response.use(handleResponse, handleError);

return { requestInterceptor, responseInterceptor };
};

// Remove interceptors
const ejectInterceptors = (requestInterceptor, responseInterceptor) => {
instance.interceptors.request.eject(requestInterceptor);
instance.interceptors.response.eject(responseInterceptor);
};

useEffect(() => {
const { requestInterceptor, responseInterceptor } = setupInterceptors();

return () => {
ejectInterceptors(requestInterceptor, responseInterceptor);
};
}, []);
};

export default useAxiosInterceptor;

이 코드를 통해 요청과 응답을 쉽게 가로채고, 필요한 로직을 추가할 수 있다.

실제 활용 예제

const api = axios.create({
baseURL: 'https://reqbin.com',
});

const App = () => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useAxiosInterceptor(api); // Set up interceptors with the axios instance

useEffect(() => {
const fetchData = async () => {
try {
const response = await api.get('/echo/get/json');
setData(response.data);
setLoading(false);
} catch (err) {
setError(err);
setLoading(false);
}
};

fetchData();
}, []);

if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;

return (
<div>
<h1>Response result</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};

export default App;

API 호출은 웹 애플리케이션에서 핵심적인 부분 이다. API 호출을 효과적으로 관리하고 최적화하는 것은 사용자 경험을 크게 향상시킬 수 있다.

useAxiosInterceptor 커스텀 훅을 활용하면 API 요청과 응답을 반복적인 코드 없이 간편하게 제어할 수 있다. 그리고 이 훅은 코드의 유지보수성을 높여주며, 잠재적인 오류를 최소화하여 사용자에게 좀 더 안정적인 서비스를 제공하는 데 도움이 되겠다.

--

--