skip to Main Content

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;

2

Answers


  1. 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>
    
    Login or Signup to reply.
  2. 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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search