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
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:
You define a
ref
to keep track of theid
. Using aref
will prevent a re-render when theid
is stored.Then, in a
useEffect
:ref
once the request has finished.redirect
function that will check the value of theref
and redirect accordingly.