Hi folks. This is my first post here! I hope you will enjoy my thoughts of software best practices π
What are the axios interceptors?
They are like simple middlewares which executes some logic before request and after responses. Interceptors are mostly used in authetication logic when we can attach some headers to every request.
axiosInstance.interceptors.request.use(
config => {
config.headers.authorization = store.get("authToken");
return config;
},
error => Promise.reject(error)
);
In react projects I often see that programmers couple redux actions with axios interceptors, so for example action loginUser can update state of store and assign authorization token to request interceptor, and on logoutUser can remove token from store and also from axios interceptors. Sounds fine? Then I will explain why not.
At first, they coupled axios and redux. Ok, butβ¦ why redux should know details about http client? And what if you want to change http client that not support interceptors? OR what if you want to use the same axios to request to another source? Do you really want to expose your auth headers? π€
Ok ok, you MAYBE have rightβ¦ but whatβs a good way to do it?
My propose to deal with it, is a magic thing called HoC. HoC is a good way to decouple your main logic from implementation details.
Your HoC can have redux state with some auth token. HoCcan dynamically set header for every request in your API Client/DataProvider without using interceptors, and then just pass your DataProvider to wrapped component, so your component can be now well tested with mocked DataProvider and without knowing anything about interceptors implementation.
The best source of HoC and example of data provider is in the official react docs https://en.reactjs.org/docs/higher-order-components.html but you can create something similar in almost every framework
Top comments (0)