React hooks to manage API call with a timer

All we need is an easy explanation of the problem, so here it is.

I need to do a fetch API call that returns a URL, do something with the returned URL, then refresh the URL after 60 seconds. This is something I could comfortably achieve without hooks, but I’d like a hooks solution.

IMPORTANT: I’m not looking to refactor this to multiple components, or create custom hooks for either the timer or API call.

EDIT: The question is – is this the correct way to handle a timer in a hooks environment? Is there a better way?

import React, { useState, useEffect } from 'react'
import { post } from 'utils/requests'

const FetchUrl = ({ id }) => {
  const [url, setUrl] = useState('')
  let [count, setCount] = useState(0)

  const tick = () => {
    let newCount = count < 60 ? count + 1 : 0
    setCount(newCount)
  }

  useEffect(() => {
    const timer = setInterval(() => tick(), 1000)

    if (count === 0) {
      post('/api/return-url/', { id: [id] })
        .then(res => {
          if (res && res.content) {
            setUrl(res.content.url)
          }
        })
    }

    return () => clearInterval(timer)
  })

  return url ? (
    <span className="btn sm">
      <a href={url} target="_blank" rel="noopener noreferrer">go</a>
    </span>
  ) : null
}

export default FetchUrl

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

See if that works for you.

I would divide that into 2 useEffect(). One to run after 1st render (similar to componentDidMount) to set the timer. And other to make the API call based on the count value.

Note: I used the ref just so I could differentiate one API call from another and add a number to it.

See snippet below:

const FetchUrl = ({ id }) => {
  const [url, setUrl] = React.useState('');
  const [count, setCount] = React.useState(0);
  const someRef = React.useRef(0);

  const tick = () => {
    //let newCount = count < 60 ? count + 1 : 0
    setCount((prevState) => prevState < 60 ? prevState +1 : 0);
  }
  
  function mockAPI() {
    return new Promise((resolve,request) => {
      someRef.current = someRef.current + 1;
      setTimeout(()=>resolve('newData from API call ' + someRef.current),1000);
    });
  }

  React.useEffect(() => {
    const timer = setInterval(() => tick(), 100);
    return () => clearInterval(timer);
  });
  
  React.useEffect(() => {
    if (count === 0) {
      /*post('/api/return-url/', { id: [id] })
        .then(res => {
          if (res && res.content) {
            setUrl(res.content.url)
          }
        })
      */
      mockAPI().then((data) => setUrl(data));
    }
  },[count]);

  return url ? (
    <span className="btn sm">
      <div>{count}</div>
      <a href={url} target="_blank" rel="noopener noreferrer">{url}</a>
    </span>
  ) : null
}

ReactDOM.render(<FetchUrl/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply