0

I have here my code that gets me the btc price

function Nft() {
    const[price,setPrice]=useState(0); 

    setTimeout(() => {
        fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd')
    .then((res)=>res.json())
    .then((response)=>{
        //your response is like this ,{"bitcoin":{"usd":18993.39}}  
    let price= response?.bitcoin?.usd;  
    setPrice(price)
    })
    .catch((error)=>{
        //here you can manage errors 
    })
      }, 12000);
  return (
    <View>
        <Text style={style.header}>Bitcoin Price</Text>
       
        <Text >{price}</Text>
     
    </View>
  );
  };

export default Nft
function Nft() {
    const[price,setPrice]=useState(0); 

    setTimeout(() => {
        fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd')
    .then((res)=>res.json())
    .then((response)=>{
        //your response is like this ,{"bitcoin":{"usd":18993.39}}  
    let price= response?.bitcoin?.usd;  
    setPrice(price)
    })
    .catch((error)=>{
        //here you can manage errors 
    })
      }, 12000);
  return (
    <View>
        <Text style={style.header}>Bitcoin Price</Text>
       
        <Text >{price}</Text>
     
    </View>
  );
  };

export default Nft

I want to update the price every 2 minutes on my UI, if I use it like it is right now, when the app loads it displays 0 for the first 2 mintes than the price gets updated, but it wont get updated every 2 minutes

HOw can i fix this?

joe joe
  • 1
  • 3
  • Does this answer your question? [setTimeout or setInterval?](https://stackoverflow.com/questions/729921/settimeout-or-setinterval) – chiliNUT Oct 21 '22 at 13:29
  • only halfway, i still need to fix that it prints out the price already when loading and than every 2 minutes – joe joe Oct 21 '22 at 17:39

1 Answers1

0

Replace the setTimeout with setInterval.

setTimeout runs only once after the given timeout.

leonardogbxv
  • 110
  • 1
  • 8
  • ok cool, but how do i ake it so that it fetches the price on loading and than update the price every 2 minutes, right now I get the useState defalut value of 2 for 2 minutes and than i get the price from api – joe joe Oct 21 '22 at 15:33