1

How to redirect to homepage after successful login in ReactJS? and also i want to show error message whenever user enter wrong credential.
I tried something like below, but it not redirect to homepage whenever user hit their right credential. and also not showing login failed prompt whenever user hit wrong credential.

It would be great if anybody could help me out what i am trying to solve is.

enter image description here

./src/Login.js

import React, {Component} from "react";
import {Form} from 'antd';


export default class App  extends Component{


  constructor(props) {
        super(props);
        this.state ={
            username: "",
            password: "",
        }
        this.onFormSubmit = this.onFormSubmit.bind(this)
    }

    onFormSubmit(values){
      console.log(values);

      const formData = new FormData();
      formData.append("username", values.username);
      formData.append("password", values.password);

        const options = {
            method: 'POST',
            body: formData
        };

       fetch('http://localhost:8000/api/login', options).then(() => {
          this.props.history.push('/home')
        }).catch((error) => {
        alert('Login Failed!')
        })


    };


 render(){
    return(

      <div>
                            <Form onFinish={this.onFormSubmit}>
                                <div class="col-md-12 form-group p_star">
                                    <Form.Item name="username">
                                      <input type="text" class="form-control" placeholder="Username"/>
                                    </Form.Item>
                                </div>
                                <div class="col-md-12 form-group p_star">
                                  <Form.Item name="password">
                                    <input type="password" class="form-control"
                                        placeholder="Password"/>
                                   </Form.Item>
                                </div>
                                <div class="col-md-12 form-group">
                                    <button type="submit" value="submit" class="btn_3">
                                        log in
                                    </button>
                                </div>
                            </Form>

     </div>

bounty
  • 89
  • 4
  • 12
  • 2
    Fetch doesn't return a rejected Promise on error HTML status (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API#Concepts_and_usage), but rather on actual network errors and aborted requests. You will need to check the response code to determine the correct course of action. – Drew Reese May 20 '20 at 08:24
  • For this specific question, I think you are required to post your API route function as well, because the way *catch* works with fetch API calls is that if your server returns a status code that is not in `200, 201, 202` and so on, then the catch will catch that specific error. Please provide the appropriate backend code and we can go from there. Thank you. – kyapwc May 20 '20 at 08:36
  • Are you getting an error or nothing at all in the console? – Zain Zafar May 20 '20 at 08:37
  • i am getting error that not redirecting to `homepage` after successful login. @ZainZafar – bounty May 20 '20 at 08:41
  • Can you share the error too? It will be helpful – Zain Zafar May 20 '20 at 08:43
  • do you use any remote application like teamviewer or anydesk? @ZainZafar – bounty May 20 '20 at 08:44
  • Yes I do but can you share screenshot of the error you are getting? – Zain Zafar May 20 '20 at 08:46
  • see the question(i have edited) .@ZainZafar – bounty May 20 '20 at 08:54
  • HTML 400 isn't an ***error***, it's a successful response with an error code, in that, the request made it to the server and the server successfully received it, processed it and responded. Fetch won't return a rejected Promise on that. See my first comment and link. – Drew Reese May 20 '20 at 09:02
  • so what is the solution of this? @DrewReese – bounty May 20 '20 at 09:04
  • From the doc I linked: "The Promise returned from `fetch()` won’t reject on HTTP error status even if the response is an HTTP `404` or `500`. Instead, it will resolve normally (with `ok` status set to `false`), and it will only reject on network failure or if anything prevented the request from completing." I.E. Check the `ok` status of the response passed to the first `then` block. – Drew Reese May 20 '20 at 09:10
  • where are you getting `this.props.history` from? history isn't a default react concept, you have to use `BrowserHistory` from `react-router` or `useHistory` from `react`. you're probably not seeing any errors cause they don't bubble up inside a promise. can you confirm you've set up history properly? – 4UmNinja May 21 '20 at 21:40
  • 1
    so i have to use `this.props.BrowserHistory.push(/home)` ?@4UmNinja – bounty May 22 '20 at 01:50
  • @4UmNinja still i am getting error. it's not redirecting to my `home` page even after i changed the function. – bounty May 24 '20 at 15:05
  • @bounty `https://reacttraining.com/react-router` is the place to go to learn how to use history for your routes. if you don't have the `BrowserRouter` (my mistake calling it `BrowserHistory`) as a provider that wraps your routes and gives you access to this.props.history in any of the routes it wraps. Can you share your index.jsx file or whatever file shows your routes eg: `` – 4UmNinja May 25 '20 at 04:15

1 Answers1

1

How to redirect to homepage after successful login in ReactJS?

  • pushing to history like the way you're doing in the example should work.

and also i want to show error message whenever user enter wrong credential.

  • there is a nice customizable library called react-toastify.
  • if you want to do your own custom error message popup, create a parent component that displays the pop-up when a function called toggleError for ex. is called.