javascriptreactjscoingecko

I want to refresh the api section every 10 secondes with React


I want to repeat this action and re-render it every 10 secondes. Can someone help me with that ?

   useEffect(() => {
  const fetchData = async () => {
    setIsLoading(true)
    const response = await coinGecko.get("/coins/markets", {
      params: {
        vs_currency: "usd",
        ids: watchList.join(","),
      }
    })
    setCoins(response.data)
    setIsLoading(false)
  }

  fetchData()
},[])

Solution

  • define a state: const [repeater,setRepeater]=useState(0) in your useEffect pass it as second argument so whenever it is changed, your useEffect would run again. Now let's take care of the 10 second intervals with this piece of code: setTimeout(() => setRepeater(prevState=>prevState+1), 100000); and finally implement it like tis:

       useEffect(() => {
      const fetchData = async () => {
        setIsLoading(true)
        const response = await coinGecko.get("/coins/markets", {
          params: {
            vs_currency: "usd",
            ids: watchList.join(","),
          }
        })
        setCoins(response.data)
        setIsLoading(false)
      }
    
      fetchData()
      setTimeout(() => setRepeater(prevState=>prevState+1), 100000);
    },[repeater])