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 token = localStorage.getItem('token');
const axiosInstance = axios.create({
baseURL: baseURL,
headers: {'Authorization': token? `Bearer ${token}`: null},
});
export default axiosInstance;
Login.js
import axiosInstance from '../../helpers/axios';
const printValues = e =>{
e.preventDefault();
axiosInstance.post('/auth', data)
.then(res =>{
console.log("writing token");
dispatch(jwtTokenRecieved(res.data.token));
localStorage.setItem('token',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 also using reducers and actions to set token into the localStorage as you see in (in addition to saving it via setItem)
dispatch(jwtTokenRecieved(res.data.token));
Update: I have tried using interceptors in axios.js after create function as follows
axiosInstance.interceptors.request.use(
config => {
console.log(config)
const token = JSON.parse(localStorage.getItem('token'));
config.headers.Authorization = token ? `Bearer ${token}`: null;
return config;
}
);
but when a new user logs in, the existing token value does not get updated with the new token and I get
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'status')