0

I am using jQuery dataTable in my project to show some data from Firestore. Everything working properly, the problem is that when some data is updated in Firestore, following alert is appearing in browser:

DataTables warning: table id=student-dataTable - Cannot reinitialise DataTable. 
For more information about this error, please see http://datatables.net/tn/3

I understand what the error is trying to say, but how do i solve the problem?

Following is my code:

$(document).ready(function() {
    var dataSet = [];
    let db = firebase.firestore();

    let query = db.collectionGroup("members").where("class", "==", "9");

    let observer = query.onSnapshot(function(querySnapshot){
        console.log("Got data");
        if (!querySnapshot.empty) {
            querySnapshot.forEach(function(doc) {
                dataSet.push([doc.data().memberName, doc.data().phone ]);
            });
        } else {
            console.log("querySnapshot in empty");
        }
        $('#student-dataTable').DataTable({
            data: dataSet,
            destroy: true,
            columns: [
                { title: "Name" },
                { title: "Phone" },
            ]
        });
    });    
  });

And the HTML code:

<table id="student-dataTable">

So can anyone help me on how to rebuild my Table when Firestore data updates. There is some info on this link,it's suggesting to use table.destroy(); but how do i use it to solve this?

I updated the code with destroy: true but when the table is reinitialized, all the data is pushed to dataSet variable each time, so every time data updates, each row is repeated in the table. How do the clean the dataSet variable each time.

Bagghi Daku
  • 652
  • 10
  • 15
  • store datatable into a variable something like this - `var table; if(table) table.destroy(); table = $('#student-dataTable').DataTable({ options...});` – Ghanshyam Singh Apr 10 '20 at 20:31
  • 1
    Does this answer your question? [Cannot reinitialise DataTable - dynamic data for datatable](https://stackoverflow.com/questions/24545792/cannot-reinitialise-datatable-dynamic-data-for-datatable) – devlin carnate Apr 10 '20 at 20:39
  • Using in `Datatable({destroy: true})` is reinitialising the table, but all the rows are repeated. – Bagghi Daku Apr 10 '20 at 20:45
  • repeated how? and have you verified that the data you're handing over to the datatable doesn't have the "repeated" rows? – devlin carnate Apr 10 '20 at 21:04
  • How do i reset the `dataSet` variable before the table is rebuild. Because it contains old data also, and new data is again pushed to `dataSet`. – Bagghi Daku Apr 10 '20 at 21:20

1 Answers1

0

You have to delete the old data before pushing to the array. Reset the array:

dataSet = [] // Inside the onSnapshot function

georgesamper
  • 4,989
  • 5
  • 40
  • 59