Using React Router to Redirect to next page after successful login

klaurtar1

I have created a basic MERN log in page and I am a bit confused on how to redirect the user after a successful log in. I have created a Log in context and when a user successfully logs in I set logged in state to true. I am unsure how I can then redirect to /items route. Any help would be appreciated. Here is my App code:

function App() {
  return (
    <LoggedInProvider>
      <ThemeProvider>
        <Switch>
          <Route
            exact
            path="/"
            render={() => <SignIn />}
          />
          <Route
            exact
            path="/items"
            render={() => <Index />}
          />
        </Switch>
      </ThemeProvider>
    </LoggedInProvider>
  );
}

export default App;

Here is my SignIn component:

function Form(props) {
  const { isDarkMode } = useContext(ThemeContext);
  const { loggedIn, changeLogIn } = useContext(LoggedInContext);
  const [isSignUp, setSignUp] = useState(false);
  const { classes } = props;

  const [usernameValue, setUsernameValue] = useState('');
  const [passwordValue, setPasswordValue] = useState('');

  const handleUsernameChange = (e) => {
    setUsernameValue(e.target.value);
  };
  const handlePasswordChange = (e) => {
    setPasswordValue(e.target.value);
  };
  // const [value, setValue] = useState(initialVal);
  //   const handleChange = (e) => {
  //       setValue(e.target.value);
  //   };

  const handleClick = () => {
    setSignUp(!isSignUp);
  };
  const reset = () => {
    setUsernameValue('');
    setPasswordValue('');
  };

  const authSubmitHandler = async (event) => {
    event.preventDefault();

    if (!isSignUp) {
      try {
        const response = await fetch('http://localhost:8181/auth', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            username: usernameValue,
            password: passwordValue,
          }),
        });

        const responseData = await response.json();
        if (responseData.code === 200) {
          console.log('Success Response');
          changeLogIn(true);
          reset();
        }
        console.log('This is a response');
        console.log(responseData);
      } catch (err) {
        console.log(err);
      }
    } else {
      try {
        const response2 = await fetch('http://localhost:8181/auth', {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            username: usernameValue,
            password: passwordValue,
          }),
        });

        const responseData2 = await response2.json();
        console.log(responseData2);
      } catch (err) {
        console.log(err);
      }
    }
  };

  return (
    <main className={classes.main}>
      {!isSignUp ? (
        <Paper
          className={classes.paper}
          style={{ background: isDarkMode ? '#2E3B55' : 'white' }}
        >
          <Avatar className={classes.avatar}>
            <LockOutlinedIcon />
          </Avatar>
          <Typography variant="h5">Sign In</Typography>
          <form
            className={classes.form}
            onSubmit={authSubmitHandler}
          >
            <FormControl
              margin="normal"
              required
              fullWidth
            >
              <InputLabel htmlFor="username">Username</InputLabel>
              <Input
                id="username1"
                name="username1"
                value={usernameValue}
                onChange={handleUsernameChange}
                autoFocus
              />
            </FormControl>
            <FormControl
              margin="normal"
              required
              fullWidth
            >
              <InputLabel htmlFor="password">Password</InputLabel>
              <Input
                id="password"
                name="password"
                type="password"
                value={passwordValue}
                onChange={handlePasswordChange}
                autoFocus
              />
            </FormControl>

            <Button
              variant="contained"
              type="submit"
              fullWidth
              color="primary"
              className={classes.submit}
            >
              Sign In
            </Button>
          </form>
          <Button
            variant="contained"
            type="submit"
            fullWidth
            color="secondary"
            className={classes.submit}
            onClick={handleClick}
          >
            Switch to Sign up
          </Button>
        </Paper>
      ) : (
        <Paper
          className={classes.paper}
          style={{ background: isDarkMode ? '#2E3B55' : 'white' }}
        >
          <Avatar className={classes.avatar}>
            <LockOutlinedIcon color="primary" />
          </Avatar>
          <Typography variant="h5">Sign Up</Typography>
          <form
            className={classes.form}
            onSubmit={authSubmitHandler}
          >
            <FormControl
              margin="normal"
              required
              fullWidth
            >
              <InputLabel htmlFor="username">Username</InputLabel>
              <Input
                id="username2"
                name="username"
                value={usernameValue}
                onChange={handleUsernameChange}
                autoFocus
              />
            </FormControl>
            <FormControl
              margin="normal"
              required
              fullWidth
            >
              <InputLabel htmlFor="password">Password</InputLabel>
              <Input
                id="password"
                name="password"
                type="password"
                value={passwordValue}
                onChange={handlePasswordChange}
                autoFocus
              />
            </FormControl>

            <Button
              variant="contained"
              type="submit"
              fullWidth
              color="primary"
              className={classes.submit}
            >
              Sign Up
            </Button>
          </form>
          <Button
            variant="contained"
            type="submit"
            fullWidth
            color="secondary"
            className={classes.submit}
            onClick={handleClick}
          >
            Switch to Sign In
          </Button>
        </Paper>
      )}
    </main>
  );
}

// class Form extends Component {
//   static contextType = LanguageContext;
//   render() {

//     return (

//     );
//   }
// }

export default withStyles(styles)(Form);

And here is my log in context:

import React, { createContext, useState } from 'react';

export const LoggedInContext = createContext();

export function LoggedInProvider(props) {
  const [loggedIn, setLoggedIn] = useState(false);
  const changeLogIn = (val) => {
    setLoggedIn(val);
  };
  return (
    <LoggedInContext.Provider value={{ loggedIn, changeLogIn }}>
      {props.children}
    </LoggedInContext.Provider>
  );
}
Muhammad Zeeshan

In your LoggedInProvider component you can do something like this:

import { useHistory } from "react-router-dom";
import React, { createContext, useState } from "react";

export const LoggedInContext = createContext();

export function LoggedInProvider(props) {
  const history = useHistory();
  const [loggedIn, setLoggedIn] = useState(false);

  const changeLogIn = (val) => {
    setLoggedIn(val);
    if(val) NavigateAway('/items');
  };

  const NavigateAway = path => {
   history.push(path);
  }

  return (
    <LoggedInContext.Provider value={{ loggedIn, changeLogIn }}>
      {props.children}
    </LoggedInContext.Provider>
  );
}

Hope this work's for you.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Reactjs redirect to dashboard page after successful login with react-router-dom (v6)

Redirect on successful login with FirebaseUI + React Router

how to redirect to a page after successful login in ReactJS?

Redirect to Login page after successful reset password

How to redirect after successful login in react js

Redirect to requested page after login using vue-router

Redirect to login page in react router 4

How to redirect to the next page after successful authentication in flutter

How to redirect to other page after successful login in angularjs?

Spring Boot redirect to current page after successful login

MediaWiki won't redirect to page after successful login

Automatic redirect after login with react-router

react-router-Dom: Blank page after redirect multiple user on login in React

Redirect after successful async action with react router v3

No Longer Navigation Works After Automatic Redirect From 404 Page to Home Page Using next/router and useEffect()

Django Redirect after Successful Login

Allow redirect after successful login

Redirecting to another page after successful login using axios in react using hooks

react redirect to another page after login

How to redirect to home after login using React( react-router v6 )?

After successful login, the url redirect to /login again

redirect to requested page after login using spring

Redirect page upon login using react-router-v5 and redux-toolkit

Change page after successful login

React Router Dom, redirect with an error message to login page and show the message there

How to redirect to the page that I want after logged in and display username after successful login

Handling Redirection after successful login using Firebase in React

How to redirect to protected route after successful login?

How to redirect user after successful login?