saving authentication data in localStorage React js

Asked

Viewed 1,273 times

0

I am developing an application in Reactjs and using Axios to work with requests and need to keep user data saved in localStorage, but something is missing in my code, as this giving Undefined in the value where was to be the data I need.

Follow the code, and my package.json

Singup index file

import React, { Component } from "react";
import { withRouter } from "react-router-dom";
var querystring = require('querystring');

import api from "../../services/api";
import { login } from "../../services/auth";
import logo from '../../../../../styles/image/logo.svg'

class SignIn extends Component {

    constructor(props) {
        super(props);
        this.state = { value: "" };
    }

    handleSignIn = async e => {
        e.preventDefault();
        const { email, password } = this.state;
        if (!email || !password) {
        this.setState({ error: "Preencha e-mail e senha para continuar!" });
        } else {
            try {            
                const response = await api.post("login", querystring.stringify({ email, password }));            
                login(response.data.token);           
                this.props.history.push("/menu");
            } catch (err) {
                this.setState({
                error:
                    "Houve um problema com o login, verifique suas credenciais. T.T"
                });
            }
        }        
    };

    render() {
        return ( 
                <div className="row"> 
                    <div className="col-md-4 offset-md-4 d-flex justify-content-center">
                        <div className='espaceblank'>
                            {/* ESPAÇO PARA SER ARRUMADO NO CSS */}
                        </div>
                    </div>
                    <div className="col-md-4 offset-md-4 d-flex justify-content-center">
                        <img src={logo} width='120' height='120' alt='logo' />                        
                    </div>
                    <div className="col-md-4 offset-md-4">
                        <p className="">Bem vindo!</p>
                                <form onSubmit={this.handleSignIn}>
                                {this.state.error && <p>{this.state.error}</p>}
                                <div className="form-group">
                                    <label>Email:</label>
                                    <input
                                        type="email"
                                        placeholder="Endereço de e-mail"
                                        onChange={e => this.setState({ email: e.target.value })}
                                        className='form-control'
                                    />
                                    <br />
                                    <label>Senha:</label>
                                    <input
                                        type="password"
                                        placeholder="Senha"
                                        onChange={e => this.setState({ password: e.target.value })}
                                        className='form-control'
                                    />
                                </div>
                                <div className='row'>
                                    <div className='col-md-4'>                            
                                        <button type="submit" className='btn btn-info waves-effect waves-light m-r-10'>Entrar</button>
                                    </div>
                                </div>
                            </form>         
                    </div>                          
                </div>
        ) 
    }
}

export default withRouter(SignIn);

Api archive

import axios from "axios";
import { getToken } from "./auth.js";

const api = axios.create({
    baseURL: "https://localhost/aplicacao",
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
});

api.interceptors.request.use(async config => {
    const token = getToken();
    if (token) {
        config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
});

export default api;

auth file

export const TOKEN_KEY = localStorage;
export const isAuthenticated = () => localStorage.getItem(TOKEN_KEY) !== null;
export const getToken = () => localStorage.getItem(TOKEN_KEY);
export const login = token => {
    localStorage.setItem(TOKEN_KEY, token);
};
export const logout = () => {
    localStorage.removeItem(TOKEN_KEY);
};

package.json file

{
  "name": "teste1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "directories": {
    "test": "test"
  },
  "scripts": {
    "build": "webpack --config webpack.prod.js",
    "start": "webpack-dev-server --config webpack.dev.js",
    "test": "jest ./test"
  },
  "jest": {
    "setupTestFrameworkScriptFile": "./test/enzyme.setup.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.2.3",
    "@babel/core": "^7.3.4",
    "@babel/plugin-proposal-class-properties": "^7.3.4",
    "@babel/preset-env": "^7.3.4",
    "@babel/preset-react": "^7.0.0",
    "babel-core": "^7.0.0-bridge.0",
    "babel-jest": "^23.6.0",
    "babel-loader": "^8.0.5",
    "babel-polyfill": "^6.26.0",
    "clean-webpack-plugin": "^1.0.0",
    "cors": "^2.8.5",
    "css-loader": "^2.0.0",
    "enzyme": "^3.6.0",
    "enzyme-adapter-react-16": "^1.5.0",
    "html-webpack-plugin": "^3.2.0",
    "jest": "^23.6.0",
    "node-sass": "^4.9.3",
    "react-router-dom": "^4.3.1",
    "react-test-renderer": "^16.8.4",
    "sass-loader": "^7.1.0",
    "style-loader": "^0.23.0",
    "url-loader": "^1.1.2",
    "webpack": "^4.27.1",
    "webpack-cli": "^3.1.2",
    "webpack-dev-server": "^3.1.8",
    "webpack-merge": "^4.1.4"
  },
  "dependencies": {
    "axios": "^0.18.0",
    "react": "^16.8.4",
    "react-check-auth": "^0.2.0-alpha.2",
    "react-dom": "^16.8.4"
  }
}

Devtools image inserir a descrição da imagem aqui

Thanks in advance for your help.

  • Opa Helder, I did not notice in your code where in fact it is called the login function of the auth file.

  • 1

    Opa André, thanks for asking, I uploaded the wrong file code, I have two equal where one is already ready and I am working on the other. But now this fixed, the login function is called in the Try catch of the handleSignIn function, in the index file of Singup.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.