Home > Mobile >  How to output fetch request response in react native
How to output fetch request response in react native

Time:10-22

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

CodePudding user response:

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>

CodePudding user response:

Please refer the following code

 fetch('https://api.coingecko.com/api/v3/simple/price? ids=bitcoin&vs_currencies=usd')
 .then((res)=>res.json())
 .then((response)=>{
     //here you can get your output of fetch in the response variable
     //whatever data you want to show here save in state variable and 
     //use that state variable to display.

 })
 .catch((error)=>{
      //here you can manage errors 
 })

**In your component you can right in this way

<Text>{your state variable}<Text>
  • Related