Reputation: 1160
I am new to web dev so please forgive.
I make simple api call
const getWorldTotal = async () => {
const response = await fetch('https://cors-anywhere.herokuapp.com/https://health-api.com/api/v1/covid-19/total');
const worldTotal = await response.json();
alert(worldTotal.total_confirmed)
document.getElementById('total') = worldTotal.total_confirmed
};
getWorldTotal()
Here is my html that i am trying to update
<div class="card text-white bg-secondary mb-3" id="total" style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body">
<h4 class="card-title" id="total"></h4>
</div>
</div>
I get the following error
index.html:80 Uncaught (in promise) ReferenceError: Invalid left-hand side in assignment at getWorldTotal
My question is what did i do wrong? Also is this the best way to update HTML when making api calls ?
Upvotes: 3
Views: 2279
Reputation: 22275
try this:
const xURL = 'https://cors-anywhere.herokuapp.com/https://health-api.com/api/v1/covid-19/total'
, total = document.getElementById('total')
;
const getWorldTotal = async () => {
let data = await (await fetch(xURL)).json()
//console.log( 'data ', data)
total.textContent = data.total_confirmed
}
getWorldTotal()
Upvotes: 3
Reputation: 307
The Document method getElementById() returns an Element object and you are trying to change it which gives you the error.
Source . Also, if you want to change the text you can use
innerText
const getWorldTotal = async () => {
const response = await fetch('https://cors-anywhere.herokuapp.com/https://health-api.com/api/v1/covid-19/total');
const worldTotal = await response.json();
alert(worldTotal.total_confirmed)
document.getElementById('total').innerText = worldTotal.total_confirmed
};
getWorldTotal()
Upvotes: 3
Reputation: 11
As Rajesh and Mr Jojo stated, I think adding ".textContent" or ".innerText" after "document.getElementById('total')" will help with this.
Also, when calling the function, you can add a semicolon to end the statement. getWorldTotal() + ";". While this is optional, it can be good to get in the habit of 'strict'.
Upvotes: 1