Every time this site loads, it gets some info in a database, sums everything and appends it in a '#total' div. I'm trying to update the value every time a new input is submitted. I thought that since the submission would occur after the site were loaded, if I tried to get the '#total' value on submit, it would be already defined but if I try to console.log it, it says it's undefined.
How could I use '#total' value after the sum were appended to it?
const route = 'http://localhost:3000';
const tot = document.getElementById('total');
serverInteraction(route).then((data) => {
data.forEach((T, i) => {
arr[i]= parseFloat(arr[i]);
console.log(T.Value);
});
var total = arr.reduce((sum, n) => sum + n);
return total;
}).then(total => appendTotal(total));
function handleSubmit(event) {
event.preventDefault();
const currentTime = new Date();
const newContent = {valor: valor.value, produto: produto.value, date: currentTime.toDateString(), time: `${currentTime.getHours()}:${currentTime.getMinutes()}`};
serverInteraction(route, 'POST', newContent);
const total = document.getElementById('total');
const inputValue = parseFloat(valor.value);
total.innerText = (total.value + inputValue);
console.log(total.value);
}
async function serverInteraction(route, method = 'GET', content = null) {
if (content) content = JSON.stringify(content);
const response = await fetch(route, {
method: method,
body: content,
headers: {"Content-type": "application/json"}
})
return response.json();
}
function appendTotal(aTotal) {
tot.append(aTotal);
}