Skip to content

Instantly share code, notes, and snippets.

@gogumai
Created May 25, 2018 12:57
Show Gist options
  • Select an option

  • Save gogumai/5dc7fdb827d7a9dcaf26063049938001 to your computer and use it in GitHub Desktop.

Select an option

Save gogumai/5dc7fdb827d7a9dcaf26063049938001 to your computer and use it in GitHub Desktop.
import axios from 'axios'
import humps from 'humps'
import Config from 'react-native-config'
import { store } from '../store'
import { setUserSession, signOut } from '../actions/auth'
const API_URL = Config.API_URL
const createAxiosClient = () => {
const userSession = store.getState().auth.userSession
let headers = { }
if (userSession) {
const { token, client, uid } = userSession
headers = {
'Access-Token': token,
'Client': client,
'Uid': uid
}
}
const client = axios.create({
baseURL: API_URL,
headers,
transformRequest: [
data => humps.decamelizeKeys(data),
...axios.defaults.transformRequest
],
transformResponse: [
...axios.defaults.transformResponse,
data => humps.camelizeKeys(data)
]
})
client.interceptors.response.use(
response => {
const { headers } = response
const token = headers['access-token']
const client = headers['client']
const uid = headers['uid']
if (token && client && uid) {
store.dispatch(setUserSession({ token, client, uid }))
}
return response
},
error => {
if (error.request.status === 401 && userSession) {
return store.dispatch(signOut())
}
return Promise.reject(error)
}
)
return client
}
export default createAxiosClient
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment