Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
like image 287
sameTbh Avatar asked Apr 16 '26 11:04

sameTbh


1 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.

like image 81
Giovanni Esposito Avatar answered Apr 18 '26 00:04

Giovanni Esposito



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!