0

Hi im messing around with some basic user authentication. I have a function which checks the database for a matching username if found it returns the user and if not returns null. my question is when a user is returned i want my app to automatically render my dashboard page, and if null to stay on the same userSelect page.

  const [enteredUserName, setenteredUserName] = useState<string>("")  

  const login = async () => {
    const response = await fetch(`http://localhost:5000/login?name=${enterUserName}`, {
      method: "GET",
    })
    const data = await response.json();
    console.log(data)
    if (data !== null) {
      console.log("user Found")
       setLoggedInUserSettings(data)
      return(
        <Link to="/dashboard"/>
      )
    } 
  };
 return (
    <>
      <div>
          <input type="text" onChange={enteredUserName} />
          <button onClick={login}>Log In</button>
      </div>

these are my routes in my App.tsx so by default the app renders the userSelect screen. and i need my app to take me to the dashboard if a user is found as the result of the login function.

     <Route exact path='/' component={UserSelect} />
     <Route path='/setup' component={UserSetUp} />
     <Route path='/tracker' component={Tracker} />
     <Route path='/history' component={History} />
     <Route path='/settings'  component={SettingsForm} />
     <Route path="/dashboard" component={Dashboard} />
   </Switch>

Thanks in advance for any help :)

2 Answers2

1

if you are working with react router you can use push function,

check this answer Programmatically navigate using react router and also react router history object

1

Instead of using <Link />, use <Redirect to="/dashboard"/> (be sure to import it from the react-router)

Or if you have your route history props available use it as the following: this.props.history.push('/dashboard'), in order to have access to history, you can wrap your component with an HOC called withRouter (withRouter docs)

Dax
  • 767
  • 4
  • 11
  • 29