How can I redirect after successful post? [React/Redux/Node/Express]

Having quite some difficulty here. Found some solutions for others, but I can’t seem to make it work. Probably not understanding state properly.

I’m trying to use react-router-dom Redirect to send the user to their dashboard once they submit a form and the POST request succeeds. I can’t put this in my fetch POST request, as that’s outside JSX scope.

I wrote a simple if(newPost) inside my form component’s render that returns Redirect to the dashboard, which worked. However, it worked across the entire app, presumably because once that newPost is successful the first time, it remains successful for all eternity.

My server-side code is separate and running on a separate domain as well.

1 Like

I think you are looking for the history property. When using the BrowserRouter component from react-router-dom the descendants receive the history prop. You can use this to change the url. Once you confirm the POST request was successful try this.props.history.push('url') where url is the relative path you would like to redirect to. Docs

Thank you, Ben. I’ll give this a shot this evening!

Okay, so I’m using the BrowserRouter component in my index.js as the Router that wraps my App component, which everything else is inside of.

I attempted using my redirect in my handleSubmit for my form component.

I received error, this.props.history is undefined.

  handleSubmit(event) {
    event.preventDefault();
    // this.setState({ alert_message: 'success' });

    const momentObj = {
      minutes: this.state.minutes,
      date: this.state.date,
      time: this.state.time,
      location: this.state.location,
      mental: this.state.mental,
      environmental: this.state.environmental
    };
    this.props.dispatch(newMoment(this.props.authToken, momentObj));
    this.props.history.push('/dashboard');
}

Its possible that only the Route components have the history prop injected. Sorry, I havent used this package in a bit. You can either pass down props from the Route, or write a method in the Route that does the redirect and pass that down, or use the withRouter HOC with will inject the history prop, also the match and location props as well. I did a Sandbox to confirm.

sandbox

I must be doing something fundamentally wrong.

Here are my Routes from app.js:

  render() {
    return (
      <div className="app">
        <HeaderBar />
        <main>
          <Switch>
            <Route exact path="/" component={LandingPage} />
            <PrivateRoute exact path="/dashboard" component={Dashboard} />
            <PrivateRoute exact path="/new-moment" component={NewMomentPage} />
            <Route exact path="/register" component={RegistrationPage} />
            <Route exact path="/login" component={LoginPage} />
          </Switch>
        </main>
      </div>
    );
  }

Now, I’m successfully redirecting when a user attempts to access a protected endpoint/component, by doing this:

const PrivateRoute = ({ component: Component, auth, ...rest }) => (
  <Route
    {...rest}
    render={props =>

      auth.isAuthenticated === true ? <Component {...props} /> : <Redirect to="/login" />
    }
  />
);

However, I just can’t get anything to work to redirect once the form’s onSubmit has successfully dispatched the action.

I’ve tried using history.push, browserHistory.push, etc., all based on multiple posts I’ve found on stackoverflow and others. They all fail at some point or another, and I have to think I’m just implementing them all wrong. I know react-router-redux has browserHistory, but I just can’t get it working.

I see your sandbox there. Now, that redirects on a simple click. But how can I have that happen only after a successful action dispatch? If I just plug it in after my dispatch in my handleSubmit, it returns undefined.

I do apologize if I’m fully misunderstanding here. :confused:

3 Likes