Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

accessing data from fetch response

When I run this code I get below response

getText(priceUrl, options)
async function getText() {
    let x = await fetch(priceUrl, options);
    let y =  x.text()

    document.getElementById("demo").innerHTML = y;
    //document.getElementById("tokenPriceUsd").innerHTML = usdPrice;
    console.log(y['nativePrice']['value'])
    document.getElementById("tokenPriceBnb").innerHTML = y['usdPrice'];


}

y is this response

{"nativePrice":{"value":"0","decimals":18,"name":"Binance Coin","symbol":"BNB"},"usdPrice":0,"exchangeAddress":"0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73","exchangeName":"PancakeSwap v2"}

now when I try to access those values to use them in my frontend

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 //document.getElementById("tokenPriceUsd").innerHTML = usdPrice;
    console.log(y['nativePrice']['value'])
    document.getElementById("tokenPriceBnb").innerHTML = y['usdPrice'];

I get

Uncaught (in promise) TypeError: y.nativePrice is undefined

I can not access the values and if I use x.json() I only get back promis object

I know there are quiet a few questions about fetch, but I still cant figure out on how to access the values from my response

>Solution :

Read up on Response.json()

You may find this helpful as well…

The Response object, in turn, does not directly contain the actual JSON response body but is instead a representation of the entire HTTP response. So, to extract the JSON body content from the Response object, we use the json() method, which returns a second promise that resolves with the result of parsing the response body text as JSON. Source

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading