I cant save my highchart chart data in localStorage

Viewed 274

I cant save data in localstorage, I get the result [object Object],[object Object],[object Object]

Here is the code

var usersonline = null;
var maxonline = 50;
Highcharts.stockChart('container', {
 chart: {
     events: {
         load: function () {

             // set up the updating of the chart each second
             var series = this.series[0];
             setInterval(function () {
                 var x = (new Date()).getTime(), // current time
                     y = Math.round(usersonline);
                 series.addPoint([x, y], true, false);
             }, 1000);
         }
     }
 },

 time: {
     useUTC: false
 },

 rangeSelector: {
     buttons: [{
         count: 1,
         type: 'hour',
         text: '1H'
     }, {
         count: 3,
         type: 'hour',
         text: '3H'
     }, {
         type: 'all',
         text: 'All'
     }],
     inputEnabled: false,
     selected: 2
 },

 title: {
     text: 'Live Chart of Players Online'
 },

 exporting: {
     enabled: false
 },
 yAxis: {
      title: 'Players Online',
      min: 0,
      plotLines: [{
         color: 'red', // Color value
         label: {
                 text: "Max Player Line"
         },
         value: maxonline, // Value of where the line will appear
         width: 2 // Width of the line    
         }]
 },
 series: [{
     name: 'Players Online',
     connectNulls: false,
     data: (function () {
         var data = [],
             time = (new Date()).getTime(),
             i;
         if (typeof(Storage) !== "undefined") {
             if (localStorage.getItem("chartdata") === null) {
                 localStorage.setItem('chartdata',[])
                 data = []
                 console.log("No Data Found, Creating Some!")
             } else {
                 data = JSON.parse(localStorage.getItem('chartdata'))
                 console.log("Chart Data Loaded.")
             }
         } else {
             console.log("localStorage is not Supported. Saving Chart Data will not work.")
         }
         // generate an array of random data
         window.onbeforeunload = function(){
             console.log("Chart data Saved")
             localStorage.chartdata = JSON.stringify(data)
         }
         return data;
     }())
 }],
 lang: {
     noData: "No Data."
 },
 noData: {
     style: {
         fontWeight: 'bold',
         fontSize: '40px',
         color: '#303030'
     }
 }
});

If I refresh the page it shows the chart as blank and It doesnt display "No Data" so there is data there but it is broken. What I want to happen is When I refresh the page it will keep the data, even when the browser or computer gets restarted.

Is there any solution to this problem, I tried multiple ways but none of them work.

This is a live data chart that I need to save data so The Chart doesnt go blank if you accidently refresh the page.

2 Answers

So the reason why when you get the item it says [Object object] is because localStorage.setItem accepts a DOMString, not an object. setItem will use toString to coerce values into a string, and Object.prototype.toString will always be [object Object].

https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem

You need to use JSON.stringify to convert your array into a valid JSON string in your localStorage.setItem function call and then use JSON.parse to parse that string when you use localStorage.getItem.

const loki = { "type": "dog", "name": "Loki" }

// Sets [object Object] in local storage
localStorage.setItem("lokiKey", loki)

// Sets "{"type":"dog","name":"Loki"}" in local storage
localStorage.setItem("lokiKey", JSON.stringify(loki))

Hope this helps!

Did you try to use myChart.addSeries ? If Series have been changed you should calling method redraw

Related