React hooks to manage API call with a timer

余生长醉 提交于 2021-02-08 03:56:23

问题


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

回答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"/>


来源:https://stackoverflow.com/questions/56903703/react-hooks-to-manage-api-call-with-a-timer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!