Search code examples
javascriptjqueryhtmlhandsontable

save handsontable to persistent state


I have created a table using handsontable:

hot = new Handsontable(container, {
        data: [],
        dataSchema: {id: null},
        startRows: 5,
        startCols: 1,
        colHeaders: ["Car"],
        columns: [
          {data: 'id'}
        ],
        rowHeaders: true,
        minSpareRows: 1,
        persistentState: true,
        onChange: function (change, source) {
            console.log(change);
            console.log(source);
        }
      });

They have a pretty elaborate example on saving/loading to/from server using ajax. However, I just want use persistent state to save load all the stuff.

In particular I want when a cell's value in hot is changed I want to save this information in some local storage, so that I can retrieve it later. The closest I got was to use change parameter in onChange and save it manually to localStorage. My main question is how can I save cell's info once it changed to some local storage? Better to persistentStorage.

Also, can I save the whole hot table to local storage? What is more efficient to update the whole table every time, or to update just the value of that particular cell? Is there a quick way to load table? Can you provide a good example how can I save/load table to local storage on change?


Solution

  • Eventually, I went with something like this:

    hot = new Handsontable(container, {
            data: [],
            dataSchema: {id: null},
            startCols: 4,
            colHeaders: ["ID"],
            columns: [
              {data: 'id'}
            ],
            rowHeaders: true,
            minSpareRows: 4,
            afterChange: function (change, source) {
                // restore table after reload of a page
                if (source === "loadData") {
                    // load data from local storage
                    if (localStorage['data']) {
                        var data = JSON.parse(localStorage['data'])
                        this.loadData(data);
                        this.render();
                        return
                    }
    
                }
                else {
                    // save all data to local storge if the edit happends
                    localStorage['data'] = JSON.stringify(this.getData());
                    return
                }
            }
        });