Add values in Firebase Realtime Database

Asked

Viewed 97 times

1

I have the following problem: I can save the user inputs in the firebase database, but I cannot sum the values in Javascript and make available in real time on the page.

I want to add the data of "age" and save in "total"

Realtime Database

var usersList = document.getElementById('usersList');
var usersNum = document.getElementById('usersNum');
var nameInput = document.getElementById('nameInput');
var ageInput = document.getElementById('ageInput');
var addButton = document.getElementById('addButton');

// Ao clicar no botão
addButton.addEventListener('click', function () {
    create(nameInput.value, ageInput.value);
});

// Função para criar um registro do pedido no Firebase
function create(name, age) {
    var data = {
        name: name,
        age: age
    };

    return firebase.database().ref().child('users').push(data);
}

firebase.database().ref('users').on('value', function (snapshot) {
    usersList.innerHTML = '';
    snapshot.forEach(function (item) {
        var li = document.createElement('li');
        li.appendChild(document.createTextNode(item.val().name + ': ' + item.val().age));
        usersList.appendChild(li);
    });
});

// Função para criar o total no Firebase
function create(totaldisp) {
    var datadisp = {
        totaldisp: totaldisp,
    };

    return firebase.database().ref().child('users').push(datadisp);
}

firebase.database().ref('users').on('value', function (snapshot) {
    usersNum.innerHTML = '';
    snapshot.forEach(function (item) {
        var li = document.createElement('li');
        li.appendChild(document.createTextNode(item.val().totaldisp + "disponíveis"));
        usersNum.appendChild(li);
    });
});


Trecho do HTML
<h1>Status dos Pedidos</h1>
    <br>
    <ul id="usersList"></ul>
    <hr>

<h1>Total de Reservas</h1>
    <br>
    <ul id="usersNum"></ul>
    <hr>

1 answer

0

There are some ways around this problem.

If you only need to show the total locally at the time of the query and not separately on another page. you do not need to update and read the database. just add directly into the internally javascript.

firebase.database().ref('users').on('value', function (snapshot) {
    let total = 0;
    // ou pode usar: total = snapshot.map(item => item.val().age).reduce((a,b) => a + b)
    usersList.innerHTML = '';
    snapshot.forEach(function (item) {
        total += item.val().age;
        var li = document.createElement('li');
        li.appendChild(document.createTextNode(item.val().name + ': ' + item.val().age));
        usersList.appendChild(li);
    });
    // seu código para atualizar o campo total aqui...
});

but if you need it in real time and synchronized with multiple users. your approach can have wrong values if simultaneous access. this sum operation cannot be performed on your client, it needs to be addressed by the server. I believe that the best method to accomplish this is to add the record is to add the sum in increment form using firebase.database.ServerValue.increment()

// Função para criar um registro do pedido no Firebase
async function create(name, age) {
    var data = {
        name: name,
        age: age
    };

    await firebase.database().ref().child('users').push(data);
    return firebase.database().ref().update({
        firebase.database.ServerValue.increment(age)
    });
}

note that I used an asynchronous function with async/await since I did two operations in the database, the ideal would be to perform a batch operation. however it would be too complex for the proposed. try this way for now.

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.