0

My app uses React Router in App.js like so:

      <Router>
        <Switch>
          <Route exact path="/">
            <Home />
          </Route>

          <Route path="/login">
            <LoginWrapper />
          </Route>

          <PrivateRoute path="/dashboard">
            <Dashboard />
          </PrivateRoute>

In my LoginWrapper component, I call a login function like so:

  doLogIn = (email, password) => {
    Auth.signIn(email, password).then(user => {
      localStorage.setItem('jwt', user.signInUserSession.accessToken.jwtToken);
    });
    // call /get-redirect endpoint here, but somehow get React Router 
   // in the parent component to see it + render the right component?
  }

After the signIn is complete, I want to call a /get-redirect endpoint in my application. That function always returns a 200, with the JSON body saying where to redirect (in response.message).

After signing in, how can I call that /get-redirect endpoint, and have React Router in my App.js render the appropriate component?

AlwaysQuestioning
  • 1,464
  • 4
  • 24
  • 48
  • make a get request to that end point then have a look at [How to redirect to a new page from function React Router](https://stackoverflow.com/a/62215486/11667949) – Shivam Jha May 02 '21 at 16:33
  • This doesn't work with my use case of dynamically populating the redirect based on the `/get-redirect` endpoint – AlwaysQuestioning May 02 '21 at 17:11

1 Answers1

0

You can use useHistory hook from react-router

import { useHistory } from "react-router-dom";

const LoginWrapper = () => {

  const history = useHistory();

  doLogIn = (email, password) => {
    Auth.signIn(email, password).then(user => {
      localStorage.setItem('jwt', user.signInUserSession.accessToken.jwtToken);
    });
    // call /get-redirect endpoint here, but somehow get React Router 
    history.push(redirectURL) //pass the URL from /get-redirect endpoint
  }

}
Abhishek Sharma
  • 158
  • 1
  • 10