Home > Software engineering >  how can I redirect the user to the page he was trying to access after sign-in?
how can I redirect the user to the page he was trying to access after sign-in?

Time:09-28

i am trying to achieve this:

case 1 (classic): the user logs in ---> is redirected to the homepage.

case 2: the user follows a link to an app page ---> is asked to log in ---> after log in is redirected to the page he was trying to access instead of the homepage.

do you have any advice on how / what I could use to do this?

what i did so far:

 const loginMutation = useMutation(loginQueries.login.fn, {
    onSuccess: enter,
    one rror: showLoginError,
})
function enter() {
    queryClient.invalidateQueries()
    history.push('/')
}

CodePudding user response:

You should catch the desired location and store it before redirecting to authentication, then provide the stored location to the LoginScreen after the user has authenticated.

I think you can find this answer useful:

CodePudding user response:

You can use the package react-router-dom. You can find extended information in internet. With it you can write something similar to this:

function App() {
  if (!token) {
    // if no token is defined, than show the login form/component
    return <Login updateToken={callbackToSetToken}></Login>;    
  } else {
    return (
      <div>
        <h1>Application</h1>
        <BrowserRouter>
          <Routes>
            <Route path="/" element={"HOME"}></Route>
            <Route path="dashboard" element={<Dashboard></Dashboard>}></Route>
            <Route path="reports" element={<Reports></Reports>}></Route>
          </Routes>
        </BrowserRouter>
      </div>
    );
  }
}

  • Related