Created
May 1, 2020 17:37
-
-
Save yoovanr/8b98a040594b0e8450d92e1e860ec55c to your computer and use it in GitHub Desktop.
[React] Axios Instance Example
This file contains 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 { Alert } from 'react-native' | |
import axios from 'axios' | |
import SocketService from './socket' | |
import store, { actions } from '../store' | |
import config from '../config' | |
const instance = axios.create({ baseURL: `${config.API_URL}/api` }) | |
instance.interceptors.request.use(handleSuccess, null) | |
instance.interceptors.response.use(null, handleError) | |
function handleSuccess (res) { | |
if (res.url.includes('login') || res.url.includes('register')) return res | |
const currentToken = store.getState().authentication.currentToken | |
if (currentToken !== null) res.headers['Authorization'] = `Bearer ${currentToken.access_token}` | |
const socket = SocketService.getSocket() | |
if (socket !== null) res.headers['X-Socket-Id'] = socket.socketId() | |
return res | |
} | |
function handleError (err) { | |
let text = 'Ooops! \n Something went wrong.' | |
const { response } = err | |
if (response) { | |
const { data, statusText } = response | |
const { message, errors } = data | |
if (errors && Object.entries(errors).length !== 0 && errors.constructor === Object) { | |
const messages = [] | |
Object.keys(errors).forEach((key) => { | |
errors[key].forEach((error) => { | |
messages.push(error) | |
}) | |
}) | |
if (messages.length) { | |
text = messages.join('\n\n') | |
} | |
} else { | |
text = message ? message : statusText | |
} | |
} | |
Alert.alert(null, text) | |
if (err.response.status === 401) { | |
store.dispatch(actions.authenticationActions.logout()) | |
} | |
return Promise.reject(err) | |
} | |
export default axiosInstance |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment