1
votes

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;
2
can u briefly explain what the problem is? cause according to code it sets the new itemkishore kingmaker
Yes, the code set the new item, but the new data don't persist untill I update the page. It's as if the old data remained in localStorage until the page refreshed. The problem is react-router-dom doesn't update when navigating the pageEdinho Rodrigues
Please add your React component which does not call render, seems that props do not get set correctly in my opinion.Mac_W
Does a new login mean logging out and then logging in?Rohit Kashyap
1. Are you sure res is not empty? 2. Are you sure res.data.data is exactly what you need to store? I am asking because it definitely removes old user_info from storage, but I am not sure if you aren't writing the undefined value back.Artem Arkhipov

2 Answers

1
votes

When you create an Axios instance you are passing in a "static" value.

        'Authorization': `Bearer ${auth_token}`,

if this value doesn't exist, it becomes

        'Authorization': `Bearer undefined`,

To fix it, you need to add an interceptor to axios to update the value of that token on EVERY request, not just on instance creation.

api.interceptors.request.use(
  config => {
    const user_info = JSON.parse(localStorage.getItem('user_info'));
    const newConf = { 
      ...config, 
      headers: {
        ...config.headers, 
        'Authorization': `Bearer ${user_info.auth_token}`,
     } 
    }
  },
  error => Promise.reject(error)
)
0
votes

I can do this using the tip of my friend JCQuintas

import axios from "axios";
import { isAuthenticated } from '../../components/Util/Auth';
export const token = 'Z31XC52XC4';

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}`
    }
});

api.interceptors.request.use(function (config) {
    console.log(config);
    if (isAuthenticated()) {
        var user_info = JSON.parse(localStorage.getItem('user_info'));
        var auth_token = user_info.auth_token;
    }
    config.headers.Authorization =  `Bearer ${auth_token}`;

    return config;
});

export default api;