I have axios instance initialized at the start of application. Under Login.js I am able to get the token and want to add it to the header using interceptors, for most subsequent api calls e.g. when using under AddSampleTable.js . (A few of them will require to go without Authorization header too e.g. ForgotPassword.js)
Currently I have to do this for every single api call in each component. My current code is as follows
axios.js
import axios from 'axios';
const baseURL = process.env.REACT_APP_BASE_URL;
let headers = {};
//this never executes since we havent logged in yet
if(localStorage.token) {
headers.Authorization = `Bearer ${localStorage.token}`;
}
const axiosInstance = axios.create({
baseURL: baseURL,
headers,
});
export default axiosInstance;
Login.js (without interceptors)
const printValues = e =>{
e.preventDefault();
axiosInstance.post('/auth', data)
.then(res =>{
console.log("writing token");
dispatch(jwtTokenRecieved(res.data.token));
const config = {
headers:{
Authorization:'Bearer '+res.data.token
}
}
axiosInstance.get('/User/GetUserByID/0', config)
.then(res =>{
dispatch(isLoggedUser(res.data));
})
.catch(err =>{
console.log(err);
})
AddSampleTable.js
This is where I want to use the instance and token should be present by default but currently I am extracting for each api call from localstorage
import axiosInstance from '../../helpers/axios';
export default function AddSamplesTable(){
const jwtToken = useSelector(state => state?.token?.data || '');
const retrieveSampleData = () =>{
const config = {
headers:{
Authorization:'Bearer '+ jwtToken,
'Content-Type': 'application/json'
}
}
axiosInstance.get('/batch/'+CoCData.id, config)
.then(function (response) {
setSamples(response.data.samples);
})
.catch(function (error) {
console.log(error);
});
}
}
Note I am using reducers and actions to set token into the localStorage as you see in
dispatch(jwtTokenRecieved(res.data.token));
