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 */
JavaScript
x
21
21
1
let localStorageData = {};
2
let localStorageDataTwo = {};
3
4
function saveLocalStorageData ({autoId, quoteId, taskId }) {
5
localStorageData = {
6
autoId: autoId,
7
quoteId: quoteId,
8
taskId: taskId,
9
}
10
return localStorageData
11
}
12
13
function saveLocalStorageDataTwo ({data}){
14
localStorageDataTwo = {
15
data : data,
16
}
17
return localStorageDataTwo
18
}
19
20
export { saveLocalStorageData, saveLocalStorageDataTwo };
21
// Saving to localStorage:
JavaScript
1
6
1
let localData = require("../../support/localStorage");
2
3
const data = "Some Data 260-255"
4
const localStorageData = localData.saveLocalStorageData({ autoId });
5
window.localStorage.setItem('localStorageData ', JSON.stringify(localStorageData ));
6
Advertisement
Answer
- You simply don’t use any strict params like
{autoId, quoteId, taskId}
just pass any arbitrarydata
. - Don’t call something
saveLocalStorageData
if that’s actually not what that function does.
Instead:
JavaScript
1
6
1
const LS = {
2
set(key, data) { localStorage[key] = JSON.stringify(data); },
3
get(key) { return JSON.parse(localStorage[key]); },
4
};
5
// export { LS };
6
JavaScript
1
20
20
1
// import { LS } from "./localstorage.js"
2
3
// Example saving multiple data in different LS keys
4
LS.set("one", {autoId: 1, quoteId: 2, taskId: 3});
5
LS.set("two", {autoId: 7});
6
7
8
// Example saving Object, and later update one property value
9
const data = {a: 1, b: 2, c: 3};
10
LS.set("single", data); // Save
11
LS.set("single", {LS.get("single"), c: 99999}); // Update
12
console.log(LS.get("single")); // {a:1, b:2, c:99999}
13
14
15
// Example saving multiple data into a single Array:
16
LS.set("arr", []); // Save wrapper Array
17
LS.set("arr", LS.get("arr").concat({a: 1, b: 2}));
18
LS.set("arr", LS.get("arr").concat({e: 7, f: 9}));
19
console.log(LS.get("arr")); // [{"a":1,"b":2}, {"e":7,"f":9}]
20
or in the last example instead of an Array you could have used an Object. It all depends on the needs.