This is the system flow:
- I log in a save the user data in localstorage.
- I got a component that read the localStorage to get a user data, like JWT.
The problem is when I do a new login, the localStorage don't update with the new data and so I can't make requisitions that use the localStorage new user data.
I found that if I update manually the page, the localStorage it's udpdated.
In the reactjs I'm using react-router-dom to navigate with the pages.
How can I get new login data to update localStorage?
//login
api.post('users/login', {email, password})//make log in
.then(res => {
localStorage.removeItem('user_info');// I remove the ond data from localStorage
if(res){//If api do the post
let data = JSON.stringify(res.data.data)
localStorage.setItem('user_info', data);//Save new data in localStorage
history.push('/');//Go the homepage
}
}).catch(error => {
this.setState({ noAuth: true })
console.log('error');
});
The component that got the user data in localStorage:
import axios from "axios";
import { isAuthenticated } from '../../components/Util/Auth';
export const token = 'Z31XC52XC4';
// var user_info = JSON.parse(localStorage.getItem('user_info'));
// var auth_token = user_info.auth_token;
// console.log(isAuthenticated);
if (isAuthenticated()) {
var user_info = JSON.parse(localStorage.getItem('user_info'));
var auth_token = user_info.auth_token;
}
const api = axios.create({
// baseURL: 'https://url-from/api/', //PRODUÇÃO
baseURL: 'https://url-from/api/', //DESENVOLVIMENTO
headers: {
'Accept': 'application/json, text/plain, */*',
'Access-Origin': 'D',
'Authorization': `Bearer ${auth_token}`,
'Company-Token': `${token}`
}
});
// console.log(user_info);
api.interceptors.request.use(
config => {
console.log(config.headers);
console.log(user_info);
const newConf = {
...config,
headers: {
...config.headers,
'Authorization': `Bearer ${auth_token}`,
}
}
// return newConf;
},
error => Promise.reject(error)
)
export default api;
res
is not empty? 2. Are you sureres.data.data
is exactly what you need to store? I am asking because it definitely removes olduser_info
from storage, but I am not sure if you aren't writing the undefined value back. – Artem Arkhipov