Home > Software design >  React router dom v5 history.push does not render new page
React router dom v5 history.push does not render new page

Time:01-06

I need to redirect user to their profile page after logging in and tried using history.push() inside Axios then. This is my code for the sign in form. I use the onClick button to get the email and password of user, and then redirect them to the new page, ClientProfile:

SignIn.js

import React from 'react';
import {Form, Button} from 'react-bootstrap';
import { useState } from 'react';
import Axios from 'axios';
import { useHistory } from 'react-router-dom';

function SignIn() {

    const history = useHistory();

  const [userEmail, setEmail] = useState("");
  const [userPassword, setPassword] = useState("");

//after onClick
  const signIn = () => {

//get user input
    Axios.post("http://localhost:8800/signIn", {
      userEmail: userEmail,
      userPassword: userPassword,
    }).then((res) => {
        console.log(res);
        history.push('/clientprofile');
  })};

    return (
        <Form>
            <Form.Group className="mb-3" controlId="formBasicEmail">
                <Form.Label>Email address</Form.Label>
                <Form.Control type="email" placeholder="Enter your email here"  
                        onChange = {(event) => {
                          setEmail(event.target.value);
                        }}
                      />
            </Form.Group>

            <Form.Group className="mb-3" controlId="formBasicPassword">
                <Form.Label>Password</Form.Label>
                <Form.Control type="password" placeholder="Enter your password here" 
                    onChange = {(event) => {
                      setPassword(event.target.value);
                    }}
                    />
            </Form.Group>
            
            <Button variant="primary" type="submit" onClick={ signIn }>
                Submit
            </Button>
        </Form>
    )
}

export default SignIn;

I define the route in app.js here:

import './App.css';
import { Navbar, Nav, Container, Image } from 'react-bootstrap';
import About from './Components/About';
import Services from './Components/Services';
import Help from './Components/Help';
import SignIn from './Components/SignIn';
import ClientProfile from './Components/ClientProfile';
import { Switch, Route, NavLink } from 'react-router-dom';

function App() {


  return (
    <div className="App">
      <Navbar className="mainNav">
                <Container>
                        <Nav className="right-side me-auto">
                            <Nav.Link as = {NavLink} to = '/' className="text-white p-3">About Us</Nav.Link>
                            <Nav.Link as = {NavLink} to = '/ourservices' className="text-white p-3">Our Services</Nav.Link>
                            <Nav.Link as = {NavLink} to = '/help' className="text-white p-3">Help</Nav.Link>
                            <Nav.Link as = {NavLink} to = '/signin' className="rounded-pill m-1 px-3 py-2 text-white signInBtn">Sign In</Nav.Link>
                        </Nav>
                </Container>
      </Navbar>
      <br/>
      
      <Switch>
        <Route exact path = "/"><About /></Route>
        <Route path = "/ourservices" ><Services /></Route>
        <Route path = "/help" ><Help /></Route>
        <Route path = "/signin"><SignIn /></Route>

//the route is being defined here
        <Route path = "/clientprofile"><ClientProfile/></Route>
      </Switch>
    </div>
  );
}

export default App;

however, it does not render a new page and instead it stays on the same page, which is Sign In page. can anyone help me?

CodePudding user response:

const signIn = () => {

//get user input
    Axios.post("http://localhost:8800/signIn", {
      userEmail: userEmail,
      userPassword: userPassword,
    }).then((res) => {
        console.log(res);
        setIsRedirect(true)

//redirect user
        if(isRedirect){
          history.push('/clientprofile');
        }
  })};

Here, inside the .then handler you are updating the state, and below it checking for the updated state.

But React updates the state asynchronously. So the updated state wont be available here.

Instead, you can use, useEffect hook and listen for updates to isRedirect state, and based on that you can perform your operations.

useEffect(()=>{

if(isRedirect){
    history.push('/clientprofile');
}

},[isRedirect,history])

CodePudding user response:

  • For the version of react router dom less than 6.^

You can use useHistory() hook like your code is showing

  • For the latest version of react router dom greater than 6.^

You can use useNavigate() hook like this.

import { useNavigate } from 'react-router-dom';

const signIn = () => {
  ....

  let navigate = useNavigate();

         .....
         ......

      navigate('/clientprofile');
    
    .....

  }

So please check your react-router-dom version in package.json file and do accordingly.

CodePudding user response:

Issue

You are submitting the form but not preventing the default form action from occurring. This reloads the page before the POST request response can be handled and the UI redirected.

Solution

Move the onClick={signIn} to the Form component and switch it to the onSubmit handler, and in the signin handler consume the onSubmit event object and prevent the default form action.

function SignIn() {
  const history = useHistory();

  const [userEmail, setEmail] = useState("");
  const [userPassword, setPassword] = useState("");

  //after onClick
  const signIn = (e) => { // <-- onSubmit event object
    e.preventDefault();   // <-- preventDefault
    // get user input
    Axios.post("http://localhost:8800/signIn", {
      userEmail: userEmail,
      userPassword: userPassword
    }).then((res) => {
      console.log(res);
      history.push("/clientprofile");
    });
  };

  return (
    <Form onSubmit={signIn}> // <-- onSubmit event handler
      ...

      <Button variant="primary" type="submit"> // <-- remove onClick handler
        Submit
      </Button>
    </Form>
  );
}

Edit react-router-dom-v5-history-push-does-not-render-new-page

  •  Tags:  
  • Related