Error with popular Array with VueJS + Firebase

1

I'm Dev RoR and I'm in my early studies with VueJS. To do so, I started creating an TodoList with Firebase for data persistence and a problem occurred to me.

I created a function to return FireBase data.

So, when there is a change or inclusion of some data in the database, Firebase returns me all the data that is presented through this Vue instance.

However, when making the first call of the function listTasks() , in line 4 in the link above, it returns the data to me correctly. But, when there is the change, the vector is not assembled again, but rather concatenated with the new values, ie, I have duplicate data.

How would you do that, whenever there was new data or change, Vue did not concatenate the vector?

I think it's something of the Vue through all the tests I've done so far. But that's just an annoyance initially.

    

asked by anonymous 12.03.2018 / 01:55

3 answers

1

The error was in the function either returning the data. Instead of the on method I used the once method. It worked the way you wanted it to. [ link

function listTasks(){
    var tasks = [];
    var listTasks = database.ref('tasks');
    listTasks.once('value', function(snapshot) {
      snapshot.forEach(function(childSnapshot) {
         tasks.push(childSnapshot.val());
      });
    });

    console.log(tasks);
    return tasks;
}
    
15.03.2018 / 03:50
0

Live,

It seems to me that the problem is that the array tasks are not being cleaned before you get the data from the database.

Try it like this:

function listTasks(){
  var listTasks = database.ref('tasks');
  listTasks.on('value', function(snapshot) {
    var tasks = [];
    snapshot.forEach(function(childSnapshot) {
       tasks.push(childSnapshot.val());
    });
});
    
12.03.2018 / 02:20
-1
methods: {
  addTodoInList: function(){
    this.tasks = []
    writeTask(11, "teste 7", "12/12/2012", 'Lorem Ipsum 3');
  }
}

function listTasks(){
  var tasks = []; // REMOVA ESSA LINHA
  var listTasks = database.ref('tasks');
  listTasks.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
       tasks.push(childSnapshot.val());
    });
  });

  console.log(tasks);
  return tasks;
}
    
12.03.2018 / 02:24