skip to Main Content

We have a React app and we need to create a page which will inform the user that they will be redirected to a specific URL in 5 seconds. That’s easy.

The tricky part is the possibility that the URL can change in the meantime. For example, the "basic" URL is https://www.someurl.com. When the page loads, I would set the timeout and that’s simple. But at the same time we should send a certain request to the backend, and the response should contain some id. IF we receive the response in 5 seconds or less, we should redirect the user to https://www.someurl.com?id=<id>. Otherwise, we should just redirect them to that basic URL.

What would be the easiest way to implement this?

2

Answers


  1. Combine two events and execute them after the timer expires.

    1: If you receive the response, save only the ID (window.responseId), and don’t redirect.

    2: When the 5s countdown is over, get the ID:

    if (window.responseId) {
      // do something
    } else {
      // do something
    }
    
    Login or Signup to reply.
  2. You define a ref to keep track of the id. Using a ref will prevent a re-render when the id is stored.

    Then, in a useEffect:

    • Call a function that will trigger the request to the backend and update the ref once the request has finished.
    • Set a timeout to run a redirect function that will check the value of the ref and redirect accordingly.
    // Define a ref to store the id fetched from backend.
    const id = useRef<number | null>(null);
    
    const fetchId = useCallback(async () => {
      const response = await fetch('https://example.com/request-to-backend');
      const id = getIdFromResponseBody(response);
      id.current = id;
    }, []);
    
    const redirect = useCallback(() => {
      if (id.current === null) {
        // Redirect to https://www.someurl.com
      } else {
        // Redirect to https://www.someurl.com?id=${id.current}
      }
    }, [id]);
    
    useEffect(() => {
      fetchId();
      setTimeout(redirect, 5000);
    }, [fetchId, redirect]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search