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
//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
CodePudding user response:
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
CodePudding user response:
You can await until the promise is resolved. Like y = await x.json()