6

I'm trying to setup a progress bar for a backend action that can take a while to complete.

  1. User click button to export a file
  2. API response has a token for the backend process
  3. With useInterval, I check every half a second the progress % (with another endpoint, sending the token) to update my progress bar component

I simplified the code in Codesandbox to reproduce the problem, in my Codesandbox, when clicking the button, I run useInterval to get a new random cat picture every 4 seconds and update my hook.

Codesandbox

As I understand, the problem is because I'm calling a Hook inside a custom Hook (useInterval), but I don't know another way to do this because native setInterval does not work with Hooks.

I used the use-interval package

1 Answer 1

9

You don't have to wrap useInterval with useEffect. Internally useInterval calls useEffect to do it work.

And you can change values passed to useInterval in component and new values will be applied correctly. You can change delay or callback arguments and useInterval will apply them.

To showcase, I've added stop button, which stops retrieving cats.

Here is working solution with cats :-)

1
  • Oh, funny that I didn't even think about putting the useInterval outside the side effect.
    – Bruno Vaz
    Commented Jul 19, 2019 at 17:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.