0

I'm using react-router-dom to help handle routing but when I try to switch to the "/" route (my home page) after the user's auth state changes, it does not trigger the redirect. Routes work otherwise throughout the app (via Links). The app is properly reflecting the user state throughout, just not redirecting.

My SignUp component is a class not functional component so I can't use hooks such as useHistory.

Here's my App.tsx:

componentDidMount() {
    auth.onAuthStateChanged((user) => {
      this.setState({ currentUser: user }, () => {
        console.log("this is running") 
        // up to here is in fact being called when there is a successful sign in
        return <Redirect to="/" />;
      });
    });
  }


render() {
    return (
      <div>
        <Header currentUser={this.state.currentUser} /> 
        <Switch>
          <Route path="/" exact={true}>
            <Home currentUser={this.state.currentUser} key={`home`} />
          </Route>
          <Route
            exact={true}
            path="/sign-up"
            component={SignUp}
            key={`sign-up`}
          />
        </Switch>
      </div>
    );
  }
}
mpc75
  • 937
  • 9
  • 22

2 Answers2

0

try to use this:

<Redirect
  to={{
     pathname: "/",
     state: { from: location }
  }}
/>
  • By "location" I imagine this case would be "sign-up"? I tried your suggestion with location = "sign-up" but unfortunately got the same result. – mpc75 Sep 05 '20 at 19:28
  • did you try leave location? Not sign-up –  Sep 05 '20 at 19:30
  • also you can try ` ` –  Sep 05 '20 at 19:31
  • Typescript won't compile if I leave it as location due to `Unexpected use of 'location' no-restricted-globals`. I tried `` but that also didn't work. – mpc75 Sep 05 '20 at 19:33
  • 1
    You can't use component in return in setState you can try with push `props.history.push("/")`. Components already have always history. So you don't declare this type in ts. –  Sep 05 '20 at 19:38
  • Thanks again, I played around with trying to get history as a prop but Typescript was a bit too finicky for me to access the `history.push()` method. I ended up solving this by going into my SignUp component and if the signup was successful then I returned `` in the render. Your comment about not being able to return a component in `setState()` set me on the right path here. I just needed to come to the realization that it wasn't just setState, rather you can only use these components inside a render. Thanks again :) – mpc75 Sep 05 '20 at 20:44
  • You are welcome. Please mark answer if its helpful for you. –  Sep 05 '20 at 21:14
0

I'm more into functional components, but you're returning a tag on auth change, right? Is this doing anything? I think the <Redirect> tag only works in a <Router> after the route has been triggered.

Maybe you can find something here: How to push to History in React Router v4?

sntrcode
  • 202
  • 1
  • 7
  • 10