React try again if error when fetching data from API

Viewed 112

Here's my page:

function MyAssets() {

  const [assetData, setAssetData] = useState({})
  const [assetArray, setAssetArray] = useState([{symbol:'', amount:''}])
  

and its component below.

I'm trying to fetch data in this component, I set a setInterval to run it every second. but requests are too many, it sometimes send back status code 429 and fail.

So I add an if statement, if I fetched data successfully, I clear this setInterval . This one failed too, it seems every time it triggers setState, the whole component render again, and my checkState become false, and triggers again.

How should I stop this component once I fetch date from API successfully?

      //React component
      function AssetRow(props) {

        const [price, setPrice] = useState(null)
        const [checkState, setCheckState] = useState(false)

        const fetchStockPrice = async()=>{
            const data = await api.getStock(props.item.symbol)
            setPrice(data.data.latestPrice)
        }

        //I try to run fetchStockPrice() every 1 second here
        useEffect(()=>{
            const doWork = setInterval(() => {
                if (checkState === false){
                    fetchStockPrice()
                    setCheckState(true)
                } else if (checkState === true) {
                    clearInterval(doWork)
                }
            }, 1000)

            return () => clearInterval(doWork) 
        }, [])


        return (
          <h1>{price}</h1>
        )
      }
0 Answers
Related