Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save API token to local storage ReactJS

Tags:

reactjs

I want to know how to save token to the local storage. I am registering and the relevant token is being generated which I have to save to the local storage. And further when I open login page there I have to fetch that to check it as well.

My code:

import React, { Component } from 'react';
import { Link } from 'react-router'
class Register extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputfirstname: '',
      inputlastname: '' ,
      inputemail: '' ,
      inputpassword: ''
    };

    this.handleFirstName = this.handleFirstName.bind(this);
    this.handleLastName = this.handleLastName.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleEmail = this.handleEmail.bind(this);
    this.handlePassword = this.handlePassword.bind(this);
  }
  static contextTypes = {
    router: React.PropTypes.object.isRequired
  }
  handleFirstName(event) {
    this.setState({inputfirstname: event.target.value});
  }
  handleLastName(event) {
    this.setState({inputlastname: event.target.value});
  }
  handleEmail(event) {
    this.setState({inputemail: event.target.value});
  }
  handlePassword(event) {
    this.setState({inputpassword: event.target.value});
  }
  handleSubmit(event) {
    fetch("http://api-env.bt2qjip33m.ap-south-1.elasticbeanstalk.com/api/v1/accounts/" , {
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        firstName: this.state.inputfirstname,
        lastName: this.state.inputlastname,
        email:this.state.inputemail,
        password: this.state.inputpassword
      })
    }).then(function(response){
      if(response.ok) {
        console.log(response)
        return response;
      }
      throw new Error('Network response was not ok.');
    }).then(function(data) { 
      console.log(data);
    }).catch(function(error) {
      console.log('There has been a problem with your fetch operation: ' + error);
    });
    alert('Submitted: ' + " " + this.state.inputfirstname +  " " + this.state.inputlastname + " " + this.state.inputemail + " " + this.state.inputpassword);
    event.preventDefault();
    this.context.router.push('/dashboard');
  }
  render() {
    return (
      <div className="container">
        <div className="row justify-content-center">
          <div className="col-md-6">
            <div className="card mx-2">
              <div className="card-block p-2">
                <center>
                <img src="./img/logos.png"/></center>
                <p className="text-muted">Create your account</p>
                <div className="input-group mb-1">
                  <span className="input-group-addon"><i className="icon-user"></i></span>
                  <input type="text" 
                  className="form-control" 
                  placeholder="First name"
                  value={this.state.inputfirstname} onChange={this.handleFirstName}
                  />
                </div>
                <div className="input-group mb-1">
                  <span className="input-group-addon"><i className="icon-user"></i></span>
                  <input type="text" 
                  className="form-control" 
                  placeholder="Last name"
                  value={this.state.inputlastname} onChange={this.handleLastName}
                  />
                </div>
                <div className="input-group mb-1">
                  <span className="input-group-addon">@</span>
                  <input type="text" 
                  className="form-control"
                   placeholder="Email"
                   value={this.state.inputemail} onChange={this.handleEmail}
                   />
                </div>
                <div className="input-group mb-1">
                  <span className="input-group-addon"><i className="icon-lock"></i></span>
                  <input type="password" 
                  className="form-control" 
                  placeholder="Password"
                  value={this.state.inputpassword} onChange={this.handlePassword}
                  />
                </div>
                <button type="button" onClick={this.handleSubmit.bind(this)} className="btn btn-block btn-success">Create Account</button>

                <center><Link to={'/pages/login'} style={{ width: 10 + '%' }} className="nav-link" activeClassName="active"><center>Login</center></Link>
</center>
              </div>
              <div className="card-footer p-2">
                <div className="row">
                  <div className="col-6">
                    <button className="btn btn-block btn-facebook" type="button"><span>facebook</span></button>
                  </div>
                  <div className="col-6">
                    <button className="btn btn-block btn-twitter" type="button"><span>twitter</span></button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
export default Register;
like image 666
Piyush Avatar asked Mar 18 '17 11:03

Piyush


1 Answers

localStorage is a global variable. You can use it in your react code just like

localStorage.setItem('itemName', value)
localStorage.getItem('itemName')
like image 128
brickingup Avatar answered Oct 07 '22 11:10

brickingup