0

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?

2
  • you can store the token on localStorage to use it across all the components. Commented May 2, 2020 at 18:23
  • you can also have a look at redux: redux.js.org/basics/usage-with-react Commented May 2, 2020 at 18:37

2 Answers 2

3

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')

Sign up to request clarification or add additional context in comments.

Comments

0

I guess the good scenario will be if you are not using redux, storing it on the localStorage and getting it across different components.

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);
              // store the token in the localstorage
              window.localStorage.setItem("token", res.data.token);
              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);

        })
      }
....

getting token in other component

const headers = {
 'Authorization': `Token window.localStorage.getItem("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})
    })
  }

(or you should create a HOC to push the token to props.)


export default withToken = (wrapperComponent) => {
   let token = window.localStorage.getItem("token");
   if(!token){
       // push to login
       this.props.history.push('/login');
   }else{
       <wrapperComponent token={token}>
   }
}

and by using the hoc you can directly access token in the props of your component.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.