Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React from 'react';
- import { Redirect } from 'react-router-dom';
- import axios from 'axios';
- export default class Login extends React.Component {
- constructor() {
- super();
- this.state = {
- authenticated: false
- }
- this.handleSubmit = this.handleSubmit.bind(this);
- this.login = this.login.bind(this);
- }
- componentWillMount() {
- if(localStorage.getItem("token")) {
- axios.post("/api/identifyToken", {
- token: localStorage.getItem("token")
- }).then(res => {
- console.log(res);
- this.setState({
- authenticated: true
- });
- }).catch(err => {
- console.log(err.response);
- this.setState({
- authenticated: false
- });
- });
- } else {
- this.setState({
- authenticated: false
- });
- }
- }
- handleSubmit(e) {
- e.preventDefault();
- this.login(this.inputUsername.value, this.inputPassword.value);
- }
- async login(username, password) {
- try {
- const response = await axios.post("/api/login", {
- username: username,
- password: password
- });
- localStorage.setItem("token", response.data.error.token);
- this.setState({
- authenticated: true
- });
- } catch(e) {
- this.setState({
- authenticated: false
- });
- console.log(e.response);
- }
- }
- render() {
- if(this.state.authenticated) {
- return <Redirect to="/home"/>;
- }
- return (
- <div>
- <form onSubmit={this.handleSubmit}>
- <label htmlFor="username">Username</label>
- <input type="text" id="usernme" ref={el => this.inputUsername = el}/>
- <label htmlFor="password">Password</label>
- <input type="text" id="password" ref={el => this.inputPassword = el}/>
- <button type="submit">Log In</button>
- </form>
- </div>
- );
- }
- }
Add Comment
Please, Sign In to add comment