Last active
September 3, 2020 11:06
-
-
Save jarretmoses/6f73caebc50e30a2ab6fd964fe4f4ae5 to your computer and use it in GitHub Desktop.
Setting a Global Auth Header to a Auth Token With React + Axios
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
// api.js | |
// @flow | |
import axios from 'axios'; | |
import { BASE_URL } from '../constants/api'; | |
type BaseFetch = { | |
url: string, | |
} | |
type BasePost = { | |
url: string, | |
data: Object | |
} | |
export const api = axios.create({ | |
baseURL: BASE_URL | |
}); | |
export const baseFetch = ({ url }: BaseFetch) => api.get(url); | |
export const basePost = ({ url, data }: BasePost) => api.post(url, data); | |
// auth.js | |
import { api } from '../services/api'; | |
/* ...code... */ | |
if (json.authorized) { | |
// Set Axios instance to use a global header | |
api.defaults.headers.common['Authorization-Header'] = json.token; | |
await dispatch(setAuthorization(json)); | |
dispatch(push(dashboardRoute)); | |
} | |
/* ...code... */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment