Chartjs-Implementing local storage in a dynamic chart – chart js

0👍

UPDATE

Please consider being more DRY (don’t repeat yourself) for example like this (incomplete) example

// Configurations
const configs = {
  label: {
    localStorageKey: 'Label',
    querySelector: '.Labelinput',
    mapper: String,
  },
  planned: {
    localStorageKey: 'plannedjobs',
    querySelector: '.planned',
    mapper: Number,
  },
  started: {
    localStorageKey: 'startedjobs',
    querySelector: '.started',
    mapper: Number,
  },
  completed: {
    localStorageKey: 'completedjobs',
    querySelector: '.completed',
    mapper: Number,
  },
};

function loadFromLocalStorage(key) {
  return JSON.parse(localStorage.getItem(key) || '[]');
}

function saveToLocalStorage(key, data) {
  localStorage.setItem(key, JSON.stringify(data));
}

function getUIData(querySelector, mapper) {
  return Array.from(document.querySelectorAll(querySelector)).map(el => mapper(el.value));
}

function setUIData(data, querySelector) {
  document.querySelectorAll(querySelector).forEach((el, i) => el.value = data[i] || '');
}

function addBarData(chart, data, whichData) {
  const idxMap = {
    "planned": 0,
    "started": 1,
    "completed": 2
  };
  chart.data.datasets[idxMap[whichData]].data = data;
  chart.update();
}

function update(event, type, chart) {
  if (event) event.preventDefault();
  const config = configs[type];
  const data = getUIData(config.querySelector, config.mapper);
  saveToLocalStorage(config.localStorageKey, data);
  addBarData(chart, data, type);
}

// Main script flow
const dataKeys = ['label', 'planned', 'started', 'completed'];
const data = dataKeys.reduce((acc, key) => {
  acc[key] = loadFromLocalStorage(configs[key].localStorageKey);
  setUIData(acc[key], configs[key].querySelector);
  return acc;
}, {});

let ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
  // ... (unchanged chart configuration)
});

// Example of how to use the update function for "planned":
// function onSomeEventForPlanned(event) {
//   update(event, 'planned', myChart);
// }

0👍

I would expect

function addBarData(chart, actualCostData, plannedCostData) {
  chart.data.datasets = [{ 
    data: actualCostData,
    backgroundColor: "#2E9CCA",
  },{
    data: plannedCostData,
    backgroundColor: "#AAABB8",
  }];
  chart.update();
}

to work better

Try this if you must

function addBarData(chart, data, whichData) {
  const idx = whichData === "actual" ? 0:1;
  chart.data.datasets[idx].data = data;
  chart.update();
} 

and 

function updateAC(event) {
  if (event) event.preventDefault();
  actualCostData = getUIACData();
  saveACToLocalStorage(actualCostData);
  addBarData(myChart, actualCostData, "actual");
}


function updatePC(event) {
  if (event) event.preventDefault();
  plannedCostData = getUIPCData();
  savePCToLocalStorage(plannedCostData);
  addBarData(myChart, plannedCostData, "planned");
}

Leave a comment