Monday, September 2, 2019

How to wait for a few seconds then redirect to another page in React


It took me a bit of thinking to make the redirect work smoothly. This is the use case in my react app, users can look at the course details info, and attempt to register a course, if user doesn't log in yet, the registration page should redirect user to a login page, after display a message that user needs to login to register for 5 seconds. Here is what we need to do:

state = {
    redirect: false // add a redirect flag
};

componentDidMount() {
    // only change the redirect flag after 5 seconds if user is not logged in
    if (!auth) {
        this.timeout = setTimeout(() => this.setState({ redirect: true }), 5000);
    }
}

componentWillUnmount() {
    // clear the timeer just in case
    clearTimeout(this.timeout);
}

render() {
    // this is the key:
    // 1. when this is first invoked, redirect flag isn't set to true until 5 seconds later
    // 2. so it will step into the first else block
    // 3. display content based on auth status, NOT based on redirect flag
    // 4. 5 seconds later, redirect flag is set to true, this is invoked again
    // 5. this time, it will get into the redirect block to go to the sign in page
    if (this.state.redirect) {
        return <Redirect to="/signin" />;
    } else {
        if (!auth) {
            return (
                <div className="center">
                    <h5>You need to login first to register a course</h5>
                </div>
            );
        } else {
            return <div>Registration Page</div>;
        }
    }
}

No comments:

Post a Comment