Search code examples
javascriptreactjsaxiostokenhttp-token-authentication

Token Authentication with Axios in React


I have created a login system in React with Axios, and it gives me a login token. I have saved this login token and response (LoginToken): (Login.js)

export default class Login extends Component {
 state = {
      redirect: false,
      redirectHR:false,
      email: "",
      password: "",
      isLogin: false,
      loggedIn: false,
      returnedEmail: "",
      returnedFirstName:"",
      returnedLastName:"",
      returnedCompanyName:"",
      returnedCompanyCode:" ",
      LoginToken:" ",
    }
        axios.post('/api/auth/login/', data, {headers:headers, withCredentials:true}).then(
          res => {
            if(res.data != null){
              console.log(res.data);
              this.setState({
                loggedIn: true,
                returnedEmail: res.data.email,
                returnedFirstName: res.data.first_name,
                returnedLastName: res.data.last_name,
                returnedCompanyName: res.data.company_name,
                returnedCompanyCode: res.data.company_code,
                LoginToken: res.data.token,  
              })
              console.log(this.state.LoginToken);
            }else{
              console.log("failed to log in");
            }
          }
        ).catch(error => {
          console.error(error.response);

        })
      }
....

Now I want to use this LoginToken as a header in another component (AdditionalInfo.js) something like:

const headers = {
 'Authorization': 'Token your_Token'
}
export class AdditionalInfo extends Component {
  state = {
    locations:[],
  }

  componentDidMount() {
    axios.get('/api/jobs/list-locations/',{headers:headers, withCredentials:true}).then(res=>{
      console.log(res)
      this.setState({locations:res.data})
    })
  }

instead of your_token, it should be the LoginToken I saved in the other component. I tried to use props but it didnt work and if I dont add this header I receive a 401 error and I can't receive info from the api. How should I import LoginToken in this file?


Solution

  • You can use localStorage Web Api to store the token and use it anywhere.

    Store it:- localStorage.setItem('LoginToken', res.data.token);

    Retrieve it:- let loginToken = localStorage.getItem('LoginToken')