Function isloggedin in react dont works

You can use the Redirect component from 'react-router-dom' to redirect from the login page to the home page if the user is logged in.

Just add a conditional return inside the render() function.

  render() {
    if (this.props.loggedIn === STATE_LOGGED_IN) {
      return <Redirect path="/home" />;
    }

    return (
      <div id="login-background">
        <Container>
    ...

I also took the liberty to refactor your components a bit. I have a few suggestions for you.

Arrow function

First, you can use arrow functions instead of class methods that require binding. Arrow functions have no this keyword, and therefore do not require binding.

  handleLogin = (data) => {
    this.setState({
      loggedIn: STATE_LOGGED_IN,
      user: data,
    });
  };

Route Children

Secondly, I advise you to use the children form of <Route> rendering. It’s much cleaner and easier to read.

      <Router>
        <Route exact path="/">
          <Login handleLogin={this.handleLogin} loggedIn={this.state.loggedIn} />
        </Route>
        <Route exact path="/logout">
          <Logout handleLogout={this.handleLogout} />
        </Route>
        <Route exact path="/home">
          <Home loggedIn={this.state.loggedIn} />
        </Route>
      </Router>

Don’t manipulate window.location

You will also notice that I removed the function that called window.location="/home". I advise you to use react-router-dom for any changes to location, instead of directly modifying window.location.

Use const strings

Finally, I advise you to const strings for your 'Logueado' and 'no-logueado' strings. By using a const, you avoid the problem of mis-typing the string.

export const STATE_LOGGED_IN = 'Logueado';
export const STATE_LOGGED_OUT = 'no-logueado';

App.js

import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import './App.css';
import Login from './Pages/Login/Login';
import Logout from './Pages/Logout/Logout';
import Home from './Pages/Home/Home';

export const STATE_LOGGED_IN = 'Logueado';
export const STATE_LOGGED_OUT = 'no-logueado';

export default class App extends Component {
  constructor() {
    super();

    this.state = {
      loggedIn: STATE_LOGGED_OUT,
      user: {},
    };
  }

  componentDidMount() {
    this.isLoggedin();
  }

  handleLogin = (data) => {
    this.setState({
      loggedIn: STATE_LOGGED_IN,
      user: data,
    });
  };

  handleLogout = () => {
    this.setState({
      loggedIn: STATE_LOGGED_OUT,
      user: {},
    });
  };

  isLoggedin = () => {
    const token = localStorage.getItem('authToken');
    if (this.state.loggedIn === STATE_LOGGED_OUT && token) {
      this.setState({
        loggedIn: STATE_LOGGED_IN,
        user: token,
      });
    }
  };

  render() {
    return (
      <Router>
        <Route exact path="/">
          <Login handleLogin={this.handleLogin} loggedIn={this.state.loggedIn} />
        </Route>
        <Route exact path="/logout">
          <Logout handleLogout={this.handleLogout} />
        </Route>
        <Route exact path="/home">
          <Home loggedIn={this.state.loggedIn} />
        </Route>
      </Router>
    );
  }
}

Login.js

Notice the conditional return in the render method.

import React, { Component } from 'react';
import Input from './Components/Input/input';
import Label from './Components/Label/Label';
import 'bootstrap/dist/css/bootstrap.min.css';
import './Login.css';
import { Container, Row, Col, Button } from 'react-bootstrap';
import { STATE_LOGGED_IN, STATE_LOGGED_OUT } from '../../App';
import { Redirect } from 'react-router';

export default class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      user: ' ',
      password: ' ',
    };
  }

  componentDidMount() {
    console.log(this.props.loggedIn);
  }

  handleChange = (name, value) => {
    if (name === 'username') {
      this.setState({ user: value });
    } else {
      this.setState({ password: value });
    }
  }

  async handleSubmit = () => {
    const requestOptions = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email: this.state.user,
        password: this.state.password,
      }),
    };

    const response = await fetch('http://localhost:4000/login', requestOptions);
    console.log(response.ok);
    if (response.ok) {
      const res = await response.json();
      localStorage.setItem('authToken', res.token);
      this.handleSuccessfullAuth(res);
    } else {
      console.log('token', localStorage.getItem('authToken'));
    }
  }

  handleSuccessfullAuth = (data) => {
    this.props.handleLogin(data);
    this.props.history.push('/home');
  }

  render() {
    if (this.props.loggedIn === STATE_LOGGED_IN) {
      return <Redirect path="/home" />;
    }

    return (
      <div id="login-background">
        <Container>
          <Row>
            <Col xs={6}>
              <Col xs={8} className="back">
                <h2 className="tittle-login">¡ Bienvenido !</h2>
                <h2 className="tittle-login">{this.props.loggedIn}</h2>
                <hr className="hr-design"></hr>
                <Label text="Usuario" />
                <Input
                  attribute={{
                    id: 'username',
                    name: 'username',
                    type: 'text',
                    placeholder: 'Ingrese su usuario ...',
                    className: 'form-control',
                  }}
                  handleChange={this.handleChange}
                />
                <Label text="Contraseña" />
                <Input
                  attribute={{
                    id: 'password',
                    name: 'password',
                    type: 'password',
                    placeholder: 'Ingrese su contraseña ...',
                    className: 'form-control',
                  }}
                  handleChange={this.handleChange}
                />
                <br></br>
                <Button variant="primary" size="lg" block onClick={this.handleSubmit}>
                  Iniciar Sesión
                </Button>{' '}
              </Col>
              <Col xs={4}></Col>
            </Col>
            <Col></Col>
          </Row>
        </Container>
      </div>
    );
  }
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top