How to use "<Redirect>" inside a function?

Viewed 268

This is my function so that when a user logs in, it checks the user's password and username and if they are both correct it should redirect to the /note url with the user ID passed through it. I have seen people use it on render(), but I would like to keep my App.jsx app simple, I think that's good practice.

I have tried using the useHistory method, but when the user inputs a data, the user needs to refresh the page manually for the new data to show. If I add a useHistory to refresh the page, it says that the location.state value is undefined.

How should I go about this problem?

Thank you

// Checking to see if current user's log info exists in db
function logIn(e) {
  e.preventDefault();
  const currentUser = users.find(
    (users) => users.username === userInput.username
  );
  if (!currentUser) {
    console.log("The Username was not found. Please try again");
  } else {
    if (currentUser.password === userInput.password) {
      // history.push("./note", { userId: currentUser._id });

      return <Redirect to={"/note/" + currentUser._id} />;
    } else {
      console.log("The password is incorrect");
    }
  }
}

Here's my routing code

import React from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

import NoteDashboard from "./NoteDashboard";
import Home from "./Home";
import CreateAccount from "./CreateAccount";

function App() {
  return (
    <Router>
      <div className="container">
        <Switch>
          <Route exact path="/" component={Home}></Route>
          <Route path="/create" component={CreateAccount}></Route>
          <Route path="/note" component={NoteDashboard}></Route>
        </Switch>
      </div>
    </Router>
  );
}

export default App;
3 Answers

The only thing (I found) you can do to redirect to a page from function is use ReactDOM.hydrate. Here an example. Example works, but only first time. After that, redirection stops to works. Maybe because codesandbox concats to url the symbol # for some technical reason that I don't know. Try to apply this solution locally an let me know if works more tha one time.

Okay I got it to work, but I don't know if this is good practice or not.

Inside the if statement where I check to see that it is the correct user, I call a function which changes a React Hook from false to true, then in my return statement, I say

{redirect ? <Redirect to={"/note/" + currentUserId} /> : null}

It seems to work fine, everything works. Does this look like a good solution or are there some flaws that I am not seeing.

Thank you for all the help.

try something like this:

state = {
            username: '',
            app_pass: '',
            redirectLink: '',
            redirect: false
        };
    componentDidMount() {
        if (window.localStorage.getItem('access_token')) {
            this.setState({ redirectLink: '/user/dashboard', redirect: true });
        }
    }

    render() {
        const { redirect } = this.state;
        const { redirectLink } = this.state;

        if (redirect) {
            return <Redirect to={redirectLink} />;
        }
}
Related