Refresh filters

Refresh filters

alexis27845alexis27845 Posts: 2Questions: 0Answers: 0

Hi im loading a lot of data so i've implemented a cache with IndexedDB so the loading is instant except for the first load then i got a function that do the api call, get the data then add/delete/update the row and the cache. To add a newRow to my dataTable i use .rows.add(toAdd).draw();

And it works great the row is added but the row is not added to the columns filter generated by dataTables.net and the row is not added to the search too. The only way i found is to force to show all the data then the filters and search works as expected, is there a way to "refresh" the filters and search ?

Replies

  • kthorngrenkthorngren Posts: 22,299Questions: 26Answers: 5,127

    The process you are using should allow the default search input to work. There are many column search solutions available. Please provide more details of what you have. A test cade showing the issues would be best.

    Kecin

  • alexis27845alexis27845 Posts: 2Questions: 0Answers: 0

    Okay so ive created a over simplified version :

    let dataTable;
    
    async function addDataToTable(data) {
      dataTable = await new DataTable("#data-table", {
        data: data,
        ordering: false,
        pageLength: 10,
        rowId: "id",
        lengthMenu: [
          [10, 50, 100, -1],
          [10, 50, 100, "Sans limite"],
        ],
        fixedHeader: true,
        initComplete: function () {
          const table = this.api();
          this.api()
            .columns()
            .every(function (index) {
              createSelect(table, this);
            });
        },
    
        columns: [
          {
            data: "id",
            width: "10px",
    
            title: "ID",
            class: "headerName",
            ordering: false,
            searchable: true,
          },
          // lot more column
        ],
      })
    }
    let refreshRunning = false;
    async function refreshData(db) {
        try {
          const response = await fetch("/getBase", { cache: "no-store" });
          if (!response.ok) throw new Error(`HTTP ${response.status}`);
    
          const resultJSON = await response.json();
          const result = {
            items: resultJSON,
            totalItems: resultJSON.length,
          };
    
          const newData = sanitize(result.items);
          const currentCache = await getAllFromCache(db);
          const currentMap = new Map(currentCache.map((i) => [i.id, i]));
          const newMap = new Map(newData.map((i) => [i.id, i]));
          const toAdd = [];
          const toUpdate = [];
          for (const item of newData) {
            const existing = currentMap.get(item.id);
            if (!existing) {
              toAdd.push(item);
            } else if (JSON.stringify(existing) !== JSON.stringify(item)) {
              toUpdate.push(item);
            }
          }
          const toDelete = currentCache.filter((i) => !newMap.has(i.id)).map((i) => i.id);
    
          if (toAdd.length) {
            dataTable.rows.add(toAdd).draw();
          }
    
          if (toUpdate.length) {
            for (const item of toUpdate) {
              const api = dataTable.rows((idx, data) => data.id === item.id);
              if (api.count()) {
                api.every(function () {
                  this.data(item);
                });
              } else {
                dataTable.rows.add([item]);
              }
            }
          }
    
          if (toDelete.length) {
            dataTable.rows((idx, data) => toDelete.includes(data.id)).remove();
          }
    
          if (toAdd.length || toUpdate.length || toDelete.length) {
            dataTable.draw();
          }
    
          if (toAdd.length || toUpdate.length) {
            await putMany(db, [...toAdd, ...toUpdate]); // Cache function
          }
          if (toDelete.length) {
            await deleteMany(db, toDelete); // Cache function
          }
        } catch (error) {
          console.error("[refreshData] Erreur lors de la mise à jour dynamique :", error);
        }
      }
    
    async function initPage() {
      const db = await openDB();
      const base = await getAllFromCache(db);
      addDataToTable(base);
      refreshData(db);
    }
    
  • kthorngrenkthorngren Posts: 22,299Questions: 26Answers: 5,127

    Looks like you are using a custom function build column select options. This is not built into datatables. However you can implement something like this thread shows:
    https://datatables.net/forums/discussion/comment/232914/#Comment_232914

    If that doesn’t help then search the forum for “buildselect” and you will find other examples.

    Kevin

Sign In or Register to comment.