How to update object value in local storage - javascript

I'm in the middle of creating a simple tv shows tracker (which ones I have seen/watching at this moment) and as I don't backend myself, I decided to store all the data in local storage.
Right now I'm able to store all the shows in the local storage with no problem. The problem occurs when I need to update data in local storage (to give you a specific example - please look at the screen below):
screenshot of my list with local storage shown
As you can see I have those buttons to adjust the number of show's seasons and episodes (they work just fine).
But I have no idea how to store that updated value and that value only in local storage.
Down below you can find the code that reads data from local storage and use them to create list:
function readFromMemory(){
const data = JSON.parse(localStorage.getItem('seriale'));
data.forEach(element => {
serialeMemory.push(element);
let serialInMemory = new SerialeList(element.pos, element.img, element.name, element.score, element.userEpisodes, element.episodes,element.userSeasons, element.seasons, element.status, element.id);
serialInMemory.inject(); //Creates list from class
serialInMemory.episodeUpDown(); //Gives functionality to episodes buttons
serialInMemory.seasonUpDown(); //Give functionality to seasons buttons
});
deleteSerialRow(); //method to delete the whole row from list and from local storage
}
I know how to filter out to show only what I want by using Array.prototype.filter method. But I don't know how to push only that row into localstorage.
I would very gladly appreciate any insight.
Thank you.

Well, since you only use one key („seriale”), there's no other way as to deserialise it, modify the object accordingly (e.g. using Array.prototype.splice), serialise it again and call localStorage.setItem with the same key and the updated and serialised object.

To be honest I kinda solved it myself.
Here's the method that works:
updateSeasons(id, changeValue){
const data = JSON.parse(localStorage.getItem('seriale'));
const filter = data.filter(element => element.id === id);
filter[0].userSeasons = changeValue;
for(let i = 0; i< serialeMemory.length; i++){
if(serialeMemory[i].id === filter[0].id) serialeMemory[i].userSeasons = changeValue;
}
localStorage.setItem('seriale', JSON.stringify(serialeMemory));
}
I've used the very same array I have kept pushing during the DOMLoad event and it works just fine.
But yeah, I probably should have attach a key to every single show, but I think I'm fine with my solution. Thank you anyway!

Related

How to not fetch all of the comments from the database all the time (how to store arrays in localstorage)

Hello I'm making a comment section on my website but I don't want to fetch all of the comments from my database when someone refreshes the page I want to solve this problem by storing comments in the array but when I use
export const comments = writable(localStorage.getItem("comments") || []);
it doesn't create an array in my local storage is there even a way to store an array in local storage with svelte or should I handle this problem differently?
If you want to store something in localstorage
user:
localstorage.setItem('comments', JSON.stringify(arr_of_cmnts);
Now, let's assume when your page opens you check if your localstorage has comments by using something like:
//In svelte
let arr_of_cmnts = [];
export const comments = writable(localStorage.getItem('comments')|| JSON.stringify(arr_of_cmnts));
//js **normally**
const cmnts = JSON.parse(localstorage.getItem('comments'));
if(cmnts && cmnts.length > 0)
//use this array
else
//call server to get comnts and store them in localstorage
In the if block how do you know if comments in localstorage are the latest???
Maybe someone has put a new comment from the last time you visited.
There maybe some solutions to this, like you inquiring db for latest comments timestamp and then checking whether the stored comments are stale or not.
Another approach of the issue (not having to query your db always) is to use a Cache (redis maybe), to serve comments, and whenever someone writes a new comment, along with updating db you can update your cache as well.
This makes read request faster.

Retrieving data objects from localstorage and reload them into array

I have taken some key points from this site already when it comes to transferring data to and from local storage. However, it does not seem to work properly. In short, I am trying to load data in the form of an array containing objects, to and from the local storage. I am aware that it is saved as a string within local storage and have then used JSON formatting to solve that problem, it is also where I think the problem might be when there is objects within objects. However, in its current state, it does not seem to work. Any ideas?
var students = [{name: "Petrina", age: "20"}];
function saveList(){
localStorage.setItem('somekey', JSON.stringify(students));
console.log("Saved to Local");
}
function loadList(){
students = JSON.parse(localStorage.getItem('somekey'));
}
The code gives no errors, I am using the functions in relation to loading the window.
window.onload = () => { loadList() }
You've added that you are calling from onload, and,
in your code you are loading into students.
add to the beginning of your code:
var students;.
Note: Some Objects need special handling.
For example: Date:
var date = new Date();
localStorage.date = JSON.stringify(date);
date = new Date(JSON.parse(localStorage.date));
Answer before additional information:
key is a method of localStorage.
Don't use it.
Use students instead, for example.
Storage.key()
(This is assuming that you call the functions)
var students = [{name: "Petrina", age: "20"}];
function saveToLocalStorage(key, value){
localStorage.setItem(key, JSON.stringify(value));
console.log("Saved to LocalStorage");
}
function loadFromLocalStorage(key){
console.log("Loaded from LocalStorage");
return JSON.parse(localStorage.getItem(key));
}
console.log("students: "+students);
saveToLocalStorage("stu", students);
var st2=loadFromLocalStorage("stu");
console.log("st2: "+st2);
cannot be run in a snippet: sandboxed, no access to localStorage - cross origin.
It got solved! - I am unsure what the problem was. I cleared all the calls for all functions and debugged the save and load function 1 at a time whilst watching the local storage data. The problem to begin with was that it simply did not save the data that got updated during runtime, hence it just kept loading values that always were the same. #iAmOren's idea by creating a function that returns a value might have done it, however I am unsure why. Thanks for the responses & Support!
Are you missing a call to your saveList function?
Calling saveList before calling loadList works as you expect.
Please refer: https://codesandbox.io/s/strange-brown-3mmeq?file=/index.html

Need to add a localStorage for my simple ToDoList

I have a simple to do app that creates to dos and displays them to the screen. However, I wan't to save these to local storage so if someone leaves the page and returns, reloads the page, etc. the to do items remain.
I need to finish it until tomorrow and i'm struggling since hours to implement a localStorage :(
I appreciate every help. Thanks in advance.
here is my code on js.fiddle.net :
if (event.target.classList.contains('js-delete-todo')) {
const itemKey = event.target.parentElement.dataset.key;
todoloeschen(itemKey);
}
https://jsfiddle.net/mymyyy/haset7gc/
You can access the window.localStorage method
By setting data to the localStorage
localStorage.setItem('key', value );
And also getting
localStorage.getItem('key', value);
You can also save an array by passing data
// let’s say am saving an array of books with objects values
localStorage.setItem('books',JSON.stringify(books));
let books = localStorage.getItem('books');
books = JSON.parse(books);
I hope this helps
To save an item to local storage:
localStorage.setItem(variable, 'value');
To get data from local storage:
let var = localStorage.getItem(variable);
Take a look at the documentation. It is really simple.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

How to duplicate a object and then save it to local storage

I have a button in my Project that duplicates a div with some content in it.
Now I want that these duplicates are somehow saved by the localStorage function. So if I refresh the Page they should still be there.
I want to create something like a ToDo list but not exactly. The princip is alike but not the same. Instead of text the user should be able to add code pieces.
Thanks for every helpful answear :)
function Function1() {
var elmnt = document.getElementsByTagName("span")[0];
var cln = elmnt.cloneNode(true);
document.body.appendChild(cln);
}
localStorage.setItem(‘myStuff’, JSON.stringify(data))
should do the trick, unless your data is not a JS object for some reason.
fetch it: const fetchedStuff = JSON.parse(localStorage.getItem(‘myStuff’))

How to save String value and print it on another page using Google Chrome storage API

I am looking to take user input in and then saving that user input using the google chrome storage api but I cannot find any useful reasources on this topic.
I have 2 elements that I would wish to save permanently using JS:
var title = encodeURIComponent(document.getElementById('title').value);
var url = encodeURIComponent(document.getElementById('url').value);
I want to create an 2 arrays, one that holds the title values and one that holds the url values, then I want to print those values out on another page.
You can use chrome.storage.local object to accomplish that.
If you need to store data in the chrome storage use the following sentence:
chrome.storage.local.set({'titles': [title]});
chrome.storage.local.set({'urls': [url]});
Now, if you want to retrieve the current data in the chrome storage use the following:
let newTile = "new title";
chrome.storage.local.get('titles', function(titles){
titles.push(newTile);
chrome.storage.local.set({'titles': titles});
});
let newUrl = "http://.....";
chrome.storage.local.get('urls', function(urls){
urls.push(newUrl);
chrome.storage.local.set({'urls': urls});
});
Important: What is missing here, are the conditions to check current data in the local storage.
Hope this helps!

Categories

Resources