Automatically redirect users to a new page using ReactJs/NextJS after a brief delay of 5 seconds

  • After a customer logs in, I want to show them a welcome page that automatically redirects them to another page after 5 seconds. To achieve this, I initially set the state with a default value of 5 seconds and then used setInterval to count down by 1 every second until it reaches 0, at which point the customer is redirected.

The issue is that console.log() always shows 5, so despite my efforts, the frontend continues to display the message: Welcome, you have successfully logged in, you will be redirected in.. 4

This discrepancy occurs because setRedirectSeconds() is asynchronous and does not update the state immediately. Consequently, each time the setInterval function restarts, redirectSeconds remains at 5.

How can I resolve this problem?

Below is the code snippet in question:

const Welcome: NextPage = (): ReactElement => {
const [redirectSeconds, setRedirectSeconds] = useState<number>(5);
const router = useRouter();
const query = router.query;

useEffect(() => {
    if (query?.redirect) {
        setTimeout(() => {
            const interval = setInterval(() => {
                console.log(redirectSeconds);
                if (redirectSeconds > 0) {
                    setRedirectSeconds(redirectSeconds - 1);
                } else {
                    clearInterval(interval);
                    router.push(query.redirect.toString());
                }
            }, 1000)
        }, 1000);
    }
}, []);

return (
        <div>
            Welcome, you have successfully logged in, you will be redirected in.. {redirectSeconds}
        </div>
);
};

export default Welcome;

Answer №1

After some adjustments, the issue has been resolved successfully:

  • I made changes by removing setInterval and utilizing the useEffect function with a dependency added. Additionally, I included a timeout of 1000ms before reducing the redirectSeconds.

     useEffect(() => {
     if (query?.redirect) {
         if (redirectSeconds == 0) {
             router.push(query.redirect.toString());
             return;
         }
    
         setTimeout(() => {
             console.log(redirectSeconds);
             setRedirectSeconds((redirectSeconds) => redirectSeconds - 1);
         }, 1000)
     }
    }, [redirectSeconds]);
    

Answer №2

Utilize the custom hook below to implement this feature.

import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';

export default function useRedirectAfterSomeSeconds(redirectTo, seconds = 5) {
  const [secondsRemaining, setSecondsRemaining] = useState(seconds);
  const router = useRouter();

  useEffect(() => {
    if (secondsRemaining === 0) router.push('/');

    const timer = setTimeout(() => {
      setSecondsRemaining((prevSecondsRemaining) => prevSecondsRemaining - 1);
      if (secondsRemaining === 1) router.push(redirectTo);
    }, 1000);

    return () => {
      clearInterval(timer);
    };
  }, [router, secondsRemaining, redirectTo]);

  return { secondsRemaining };
}

Here is an example of how to use it:

import Head from 'next/head';
import useRedirectAfterSomeSeconds from '../hooks/useRedirectAfterSomeSeconds';

export default function ErrorPage() {
  const { secondsRemaining } = useRedirectAfterSomeSeconds('/', 5);

  return (
    <>
      <Head>
        <title>Page not found - redirecting in 5 seconds</title>
      </Head>
      <main>
        <h1>404</h1>
        <p>
          This page cannot be found. Redirecting to homepage in
          {secondsRemaining} {secondsRemaining > 1 ? 'seconds' : 'second'}.
        </p>
      </main>
    </>
  );
}

Answer №3

Declare a state variable at the top level. When it reaches 0, direct the user to another page

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

const [count, setCount] = useState(5);

In the useEffect hook, create a setInterval function to decrement count by 1 every 1000ms

const navigate = useNavigate();
useEffect(()=>{
   // decrement count by 1 each second
   const interval=setInterval(()=>{
            setCount((updatedCount)=>updatedCount-1)
        },1000)
    // if count reaches 0, redirect

    count==0 && navigate(`/${query.redirect.toString()}`)

    // always clear the intervals in the clean-up function
    return ()=>{
          clearInterval(interval)
    }

},[count,navigate])

Display a message on the page.

<p>
This page is not available. Redirecting to homepage in
{count} {count > 1 ? 'seconds' : 'second'}.
</p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Every time I try to create a new React app, I consistently run into the same error

I keep encountering this error every time I try to create a React app using create-react-app. ...

Error encountered: The module '@mui/x-data-grid' does not export 'GridActionsCellItem'

I'm facing an issue while trying to import 'GridActionsCellItem' from '@mui/x-data-grid'. Here's the code: import { GridActionsCellItem } from '@mui/x-data-grid'; An error message pops up indicating: Attempted impor ...

Create a custom element in React to detect and encapsulate links

I could really use some assistance with this issue. I have a bunch of text blocks containing links and have been utilizing linkifyjs's React component to automatically wrap the links in anchor tags. However, now I am looking to add a custom button nex ...

Parent-sourced Material Tooltip Text Display

I would like to implement a ToolTip in the following manner: const MyComponent = () => { [open, setOpen] = useState(false); return <div (onClick)={() => {setOpen(!open)}> Click to open tooltip <Tooltip text="some ...

Guide on implementing a shared layout in NextJS with Auth0 integration

After following the Next docs to configure my layouts successfully, I encountered an issue with the NextJS Auth0 SDK's withPageAuthRequired wrapper that disrupts this setup. The layout pattern I've implemented is based on the guidelines outlined ...

Create a left-aligned div that spans the entire width of the screen, adjusting its width based on the screen size and positioning it slightly

I have a parent container with two child elements inside. I want the first child to align to the left side and the second child to align to the right side, but not starting from the exact center point. They should be positioned slightly off-center by -100p ...

What is causing the issue with Shallow routing in Nextjs?

I've been experimenting with Shallow routing in Next.js to update the state in the URL without actually navigating to a new page, but I'm encountering unexpected behavior. In the scenario outlined below, I start on the home page using the URL: l ...

What is the best way to retrieve a cookie sent from the server on a subdomain's domain within the client request headers using getServerSideProps

Currently, I have an express application using express-session running on my server hosted at api.example.com, along with a NextJS application hosted at example.com. While everything functions smoothly locally with the server setting a cookie that can be r ...

Next.js with Express Application Deployment to Elastic Beanstalk: Troubleshooting Error 502

I am encountering persistent 502 Bad Gateway errors while attempting to deploy a next.js application using express to Electric Beanstalk. 2020/03/02 15:26:28 [error] 8286#0: *172 connect() failed (111: Connection refused) while connecting to upstream, ...

I am running into an issue where the Google App Engine standard is not able to compress my Next.js/Express

I am currently exploring solutions to enable compression on the output of my Next.js/Node.js/Express application when deployed on Google App Engine (standard version). It appears that the issue lies in the fact that: 1) Google's load balancer strips ...

Steps to transition from dynamic routing to static routing in Next.js

Is there a way to change the status of the current user using /users/[id]/activity as an example? I attempted to use http://localhost:3000/api/users/1/activity but received a 404 error page. How can I find the correct path and extract the id from the prev ...

Encountering an error when attempting to utilize material icons, specifically related to an invalid

I have just started learning reactjs and I am facing an issue while trying to add a material icon in my code. Every time I do that, it gives me an error message saying ss of errorInvalid hook cell Navbaar.js import React from 'react' imp ...

Can the MUI autocomplete feature be connected to two different field values simultaneously?

Hello there! I am currently working on creating a unique custom search input that will provide users with filter categories to select from when clicked. Users will also have the option to enter a title keyword to refine their search based on both the title ...

What is the method for adding a class in react using material makeStyles css?

Check out these awesome styles I created const customStyles = makeStyles({ button1: { border: 0, position: 'relative', overflow: ' hidden', color: '#FFF', backgroundColor: '#7768F2', &apo ...

The deployment is being effortlessly conquered by React-HTML-Parser

I am encountering an issue while trying to deploy my next app on vercel, as the react-html-parser is causing errors. I considered downloading an older version of React, but there are other dependencies that require the latest version. Is there a solution ...

Having trouble with the `npm start` command while working with react.js?

Currently, I am in the process of setting up React.js. To achieve this, I executed npm install -g create-react-app followed by create-react-app my-app. Afterward, I proceeded to run the npm start command but encountered the error displayed below. https:// ...

Is there a method for uploading and viewing files from a server using the MERN stack?

Looking to create a functionality for users to upload various file types such as documents, presentations, and text files, save them to a database, and then view them from the server. Are there any recommended frameworks or npm modules to help with this ...

Upon entering the command "amplify", an alert was triggered displaying the following message: "DeprecationWarning: Invalid 'main' field in .....". This warning

Every time I type amplify console in my react-app, I encounter this warning message. >amplify console (node:2500) [DEP0128] DeprecationWarning: Invalid 'main' field in 'C:\Users\SAMSUNG\AppData\Roaming\np ...

What are the steps to developing a chat application with MERN stack or another straightforward method?

What is the best way to develop a chat application for direct communication between two individuals? For instance, imagine a website with numerous producers where a consumer wishes to engage in a live chat with a specific producer. Any ideas on how to ach ...

Transform inline styles in React to CSS declarations

Is there a tool available that can convert React inline style descriptions into CSS rules? For example: { minHeight: 200, position: 'relative', flexGrow: 1, flexShrink: 1, display: 'flex', flexDirection: ' ...