Reputation: 149
I have two different lists on my page, which data I want to store in Local Storage. With this code below I store my data from one list. How can I use this code to store this data from two lists, but to be in separate objects? maybe this question is silly, but i'm a beginner. Thanks for your help.
class Storage {
saveStorage(task) {
const tasks= this.getFromStorage();
tasks.push(task);
localStorage.setItem('tasks', JSON.stringify(tasks));
}
removeStorage(task){
const tasks= this.getFromStorage();
recipes.forEach((task, index) => {
if(task === task.id) {
tasks.splice(index,1);
}
});
localStorage.setItem('tasks', JSON.stringify(tasks));
}
getStorage() {
let tasks;
if(localStorage.getItem('tasks') === null) {
tasks= [];
} else {
tasks= JSON.parse(localStorage.getItem('tasks'));
}
return tasks;
}
}
Upvotes: 0
Views: 717
Reputation: 4773
I would use something more generic. With "tasks" hard-coded in there, it makes things difficult to reuse. Also, this is built so all stored data MUST be an array or items in an array - I would change it to handle all types. If you want to inject something into an array, I would think you can and should do that outside of the Storage class and just save again. Also, complex objects will need to be "revived" when pulled back out.
One other thing to note is that you may run into the "JSON Graph Problem" because JSON doesn't store object reference data. Use this with care. Here's a little more information on that: http://netflix.github.io/falcor/documentation/jsongraph.html.
See the example code below and here's a working jsfiddle to demonstrate: https://jsfiddle.net/wd4acLfv/45/
class Storage {
static get(key, reviveFuncOrDefault = null) {
const itemJSON = localStorage.getItem(key)
if (reviveFuncOrDefault !== null) {
if (itemJSON === null)
return reviveFuncOrDefault
else if (typeof reviveFuncOrDefault === 'function')
return reviveFuncOrDefault(JSON.parse(itemJSON))
}
return JSON.parse(itemJSON)
}
static set(key, item) {
localStorage.setItem(key, JSON.stringify(item))
}
static unset(key) {
localStorage.removeItem(key)
}
}
// Plain Object
Storage.set('obj', { foo: 'bar '}) // Set object
console.log(Storage.get('obj', {})) // Object exists
console.log(Storage.get('obj2', {})) // Object fallback value
// Primitive Type
Storage.set('bool', true) // Set array
console.log(Storage.get('bool', false)) // Array exists
console.log(Storage.get('bool2', false)) // Array fallback value
// Array
Storage.set('arr', [ 1, 2, 3 ]) // Set array
console.log(Storage.get('arr', [])) // Array exists
console.log(Storage.get('arr2', [])) // Array fallback value
// Mutate array
const arr = Storage.get('arr', [])
arr.push(4)
Storage.set('arr', arr)
console.log(Storage.get('arr', []))
// Non-plain JS Object
class Person {
constructor(firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
getFullName() {
return this.firstName + ' ' + this.lastName
}
}
Storage.set('person', new Person('Bob', 'Ross')) // Set object
const person = Storage.get('person',
({ firstName, lastName }) => new Person(firstName, lastName)
)
console.log(person.getFullName())
Upvotes: 0
Reputation: 138267
Pass a name into the constructor, e.g.:
constructor(name) { this.name = name; }
Then replace tasks
with this.name
everywhere, e.g.:
localStorage.getItem(this.name)
Then you can just do:
const tasks = new Storage("tasks");
const users = new Storage("users");
Upvotes: 1
Reputation: 1818
Try something like this that is a little more generic and reusable.
class Storage {
static saveStorage(obj, key) {
const store = Storage.getFromStorage(key);
store.push(obj);
localStorage.setItem(key, JSON.stringify(store));
}
static removeStorage(obj, key, fnCompare) {
const store = Storage.getFromStorage(key);
store.forEach((item, index) => {
if (fnCompare && fnCompare(obj, item)) {
store.splice(index, 1);
} else if (item == obj) {
store.splice(index, 1);
}
});
Storage.saveStorate(store, key);
}
static getFromStorage(key) {
if (localStorage.getItem(key) === null) {
return [];
} else {
return JSON.parse(localStorage.getItem(key));
}
}
}
Then you can call it like this:
Storage.saveStorage({ test: 'true'}, 'test');
Storage.removeStorage({ test: 'true'}, 'test', function(curr, prev) { return curr.test == prev.test});
Storage.getFromStorage('test')
Upvotes: 0
Reputation: 452
If I understand your question correct, you need to adjust your structure of your functions to take in a parameter that defines the list you want to edit.
You storage should then contain an Array
of Objects
, and each object needs to have an identifier, such as a name or ID that can then be used to identify the different lists.
You would then need to pass them to your functions to modify and retrieve. Pass in that exact ID or name and your functions code should then be made to look for the right object in the array. Can easily be done with array.find
, such as someArray.find(x = >x.name === "List1")
.
Hope it helps.
Upvotes: 0