React hook은 react 컴포넌트 or custom hooks이 아닌 경우 사용할 수 없다.
그래서 axios interceptor에서 hook을 사용할 수 없다. 😐
하지만 내가 써야겠다면?!?!?!?!🙄
너무 길어져서 몇 부분은 ...으로 대체했다. 🙄
const instance = axios.create({
baseURL: "http://localhost:8080"
})
instance.interceptors.request.use((config) => {
const token = useSelector((state) => state.user.value);
const dispatch = useDispatch();
if (token.accessToken){
if (...){
axios.get("...", {headers: {Authorization: `Bearer ${token.accessToken}`}})
.then((res) => {
dispatch(login({
...}));
})
}
}
return config;
})
내가 꼭꼭 useSelector()랑 useDispatch()를 써야겠다면? 😊
아무도 날 말릴 수 없으삼.
구글링 조져
✨나의 은인 -> 출처 - dev.to✨
사실 위 글 말고도 다른 방법들이 있었는데... index.js 나 App.js에 코드 추가를 하기가 싫어서 최대한 깔끔한 걸 찾아서 했다.
const instance = axios.create({
baseURL: "http://localhost:8080"
})
function Interceptor({children}) {
return children;
}
export default instance;
export {AxiosInterceptor}
react component를 만들어준다! 리턴할 거 없다 캬캬 😑
포인트는 이 컴포넌트 안에 인터셉터를 만들어주는 거다!!!
const instance = axios.create({
baseURL: BASE_URL
})
const Interceptor = ({children}) => {
const dispatch = useDispatch();
const token = useSelector((state) => state.user.value);
useEffect(() => {
const interceptor = instance.interceptors.request.use(
function (config) {
if (...){
axios.get("...", {headers: {Authorization: `Bearer ${token.accessToken}`}})
.then((res) => {
dispatch(login({...}));
})
}
config.headers.Authorization = `Bearer ${token.accessToken}`;
return config;
},
function (error) {
...
}
);
}, [])
return children;
}
export default instance;
export {Interceptor};
interceptor가 component안에 있기 때문에 useEffect를 사용해서 axios instance에 추가한다!
App.js
import {Interceptor} from "./utils/api";
function App() {
return (
<Interceptor>
<Router>
<Routes>
<Route path="/" element={...} />
...
</Routes>
</Router>
</Interceptor>
);
}
App.js 내부를 감싸준다!
아주 잘 작동된다! 야호!!
끝!😊