Search code examples
react-nativefetch

How to output fetch request response in react native


I want to print out the response of my fetch request in react native.

How would I do this to get the response inside a Text?

function Nft() {
  fetch(
    "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"
  );
  return (
    <View>
      <Text style={style.header}>Bitcoin Price</Text>
    </View>
  );
}

export default Nft;

Solution

  • Define state variable like following

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

    then replace fetch code by following

     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 
     })
    

    In your component you can right in this way

    <Text>{price}<Text>