Skip to content

Single function for saving into localStorage?

How can we save and retain localStorage objects rather than creating multiple functions ? The first localStorage object get replaced with the new save. So to avoid that I have created a new function called saveLocalStorageDataTwo which is working. But how can we avoid creating multiple functions for saving data into the localStorage ? Is there any way ? Could some please advise ?

/* localStorage.js */

let localStorageData = {};
let localStorageDataTwo = {};

function saveLocalStorageData ({autoId, quoteId, taskId }) {
    localStorageData = {
        autoId: autoId,
        quoteId: quoteId,
        taskId: taskId,
    }
    return localStorageData
}

function saveLocalStorageDataTwo ({data}){
    localStorageDataTwo = {
        data : data,
    }
    return localStorageDataTwo
}

export { saveLocalStorageData, saveLocalStorageDataTwo };

// Saving to localStorage:

let localData = require("../../support/localStorage");

const data = "Some Data 260-255"
const localStorageData = localData.saveLocalStorageData({ autoId });
window.localStorage.setItem('localStorageData ', JSON.stringify(localStorageData ));

enter image description here

Answer

  • You simply don’t use any strict params like {autoId, quoteId, taskId} just pass any arbitrary data.
  • Don’t call something saveLocalStorageData if that’s actually not what that function does.

Instead:

const LS = {
  set(key, data) { localStorage[key] = JSON.stringify(data); },
  get(key) { return JSON.parse(localStorage[key]); },
};
// export { LS };
// import { LS } from "./localstorage.js"

// Example saving multiple data in different LS keys
LS.set("one", {autoId: 1, quoteId: 2, taskId: 3});
LS.set("two", {autoId: 7});


// Example saving Object, and later update one property value
const data = {a: 1, b: 2, c: 3};
LS.set("single", data); // Save
LS.set("single", {...LS.get("single"), c: 99999}); // Update
console.log(LS.get("single")); // {a:1, b:2, c:99999}


// Example saving multiple data into a single Array:
LS.set("arr", []); // Save wrapper Array
LS.set("arr", LS.get("arr").concat({a: 1, b: 2}));
LS.set("arr", LS.get("arr").concat({e: 7, f: 9}));
console.log(LS.get("arr")); // [{"a":1,"b":2}, {"e":7,"f":9}]

jsFiddle playground

or in the last example instead of an Array you could have used an Object. It all depends on the needs.