Search code examples
reactjstimerpush

Delay a push to a page on success


I am currently working on pushing to a log in page on the confirmation of a user via email. Problem is, I would like to first re-direct the user confirming to a page thanking them for registering and a few seconds later push to the log in page. What's the best way of approaching this?

I have a push to the log in page that is happening right away, would like to delay it a few seconds.

 confirmSuccess = () => {
this.setState(() => ({ success: true }));
this.props.history.push("/login", { fromRegistration: true });
 };

Currently as soon as the user clicks on "confirm account" it pushes them straight the log in page, would like to have it delayed so the "thank you for registering" page can appear first.


Solution

  • You can create a new component like this

    import React from "react"
    import { withRouter } from "react-router-dom"
    
    class ThankYouComponent extends React.Component {
      componentDidMount() {
        setTimeout(() => {this.props.history.push("/login")}, 5000) // redirect in 5 secs
      }
    
      render() {
        return(
          <h1>Thank You</h1>
        )
      }
    }
    
    export default withRouter(ThankYouComponent)
    

    and in your confirmSuccess function redirect to ThankYouComponent page instead:

    confirmSuccess = () => {
      this.setState(() => ({ success: true }));
      this.props.history.push("/thankYouPage", { fromRegistration: true });
    };
    

    And of course don't forget to add ThankYouComponent to Routes