Created
May 27, 2018 12:14
-
-
Save amitava82/b8daed4375fde5eb5ecdb3e9e6babb62 to your computer and use it in GitHub Desktop.
how to use axios interceptor with redux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from 'axios'; | |
import get from 'lodash/get'; | |
import set from 'lodash/set'; | |
import qs from 'qs'; | |
axios.defaults.baseURL = process.env.REACT_APP_API_URL; | |
axios.defaults.paramsSerializer = params => qs.stringify(params, { arrayFormat: 'brackets' }); | |
const addAuthorizationToHeaders = (state, config) => { | |
const userToken = get(state, 'session.user.token', null); | |
if (!userToken) { | |
return config; | |
} | |
set(config, 'headers.token', userToken); | |
return config; | |
}; | |
const authorizationProvider = (store) => { | |
axios.interceptors.request.use((config) => { | |
const state = store.getState(store); | |
return addAuthorizationToHeaders(state, config); | |
}); | |
}; | |
export default authorizationProvider; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment