Hello! I’m making a To Do List and I’m trying to figure out if it’s possible to put newly created elements into LocalStorage, so that it can stay on a page refresh. I don’t know if you can because I’ve been at this for a month, and I’ve been researching online about it but I haven’t found anything about being able to save created elements to localstorage. I think I’m still really confused on how localstorage works, and I need some help. Thanks!
Local Storage is a key/value storage in which the keys are strings, and the values are strings. I haven’t looked at your pen but I’m going to assume you’re trying to save object values which is not going to work. Instead of saving element objects, I think you should try to simplify the state down to a JavaScript array.
For example if your state was represented with the following:
const todoList = [
{
name: 'take out the dog',
completed: false,
},
{
name: 'walk the trash',
completed: true,
}
};
then you could save it to Local Storage by JSON stringifying it:
localStorage.set('todoList', JSON.stringify(todoList));
when you retrieve it you’ll need to parse it to get an object again:
JSON.parse(localStorage.get('todoList'));
Once you’ve retrieved the list from localStorage, then you can render to the DOM .
okay that sounds good. I’m testing something out right now and it looks like when I try to push my item bar values into an array to parse it, retrieve it, and then assign the array values to my paragraph values, it doesn’t seem to stick around even though the array is parsed. I think I understand what you mean though.
So, I’m currently just testing out what you explained in your example, and it looks like when I push the items
value to an array in an object form and refresh the page, it appears that the first set of pushed items don’t save when I try to add more items to the array in the search bar. Is the way I’m doing it is correct, or is what I’m attempting to do not possible
const items = document.getElementById("count");
const submission = document.getElementById("submit-button");
const clear = document.getElementById("clear");
const task = document.getElementById("tasks");
let counter = 0;
var nietos = [];
function submit(){
const nieto = {
value: items.value
}
var obj = {};
obj["02"] = nieto.value;
nietos.push(obj);
localStorage.setItem('todoList', JSON.stringify(nietos));
console.log(nietos)
const p = document.createElement("p");
p.innerHTML = JSON.parse(localStorage.getItem('todoList'));
task.appendChild(p)
}
document.getElementById('submit-button').addEventListener('click', function () {
if(items.value !== ""){
submit();
counter++
}
localStorage.setItem("counter", counter);
});
yeah, no problem! A Pen by Brandon (codepen.io)
Right, and this is the part that I’m stumped for a month because I have no idea how to retrieve an exisitng localstorage value and I’ve tried everything that I can think of.
Yeah, I’m kind of just testing something out in this code, but those things that you’ve mentioned are just parts of different code that I just decided to leave there for now
I’m testing to see if I can visually check if the existing localstorage value are saving by creating and appending a paragraph element to the page
it parses the existing localstorage values so that they can stay on refresh, however on a refresh the values overwrite (which I can view in the Application section of the inspect when you right click your mouse). And does what you mentioned here
JSON.parse(localStorage.getItem(‘todoList’))
gotcha so something like this?
window.addEventListener('reload', e =>{
if(JSON.parse(localStorage.getItem('todoList')) !==""){
nietos = JSON.parse(localStorage.getItem('todoList'));
} else{
nietos = [];
}
})
Ok great! So how can I check to see if it worked? Would I just console.log`` nietos
on reload?
correct, I tried the former and I’m just doing objects because I’m follow the first guy’s example at the beginning of the thread
Basically, this is the original ToDoList program that I was working on where I originally stated that whenever I reloaded the page, the paragraph values would not stay on refresh. So pretty much the first guy was responding to this.
Edit: fixed it to where p.innerhtml
is assigned to items.value
So do you mean turn the whole ToDoList into an array? With the buttons included insided the array too, or should the word values just be inside the array?
No, I’m suggesting you have one source of truth, the state of your data (which could look like the array I suggested above). Anytime you render (add/edit/delete elements on the DOM), you should be referring to that state in order to determine what to render.
Ideally, managing state, managing localStorage, and managing the DOM should all be separate functions. In other words, when the user types into the textbox and clicks submit, there should be a function call to update the state, a separate function call to render to the DOM (based on the new state), and another separate function call to update the localStorage (again, based on the new state).
Okay, gotcha. So all the different programs (managing the DOM, localStorage, etc.) should be in different functions, right? That’s basically what state is, got it. If so, I’m still not really sure how your able to put items.value
to LS so that when the user inputs it submits it, it can automatically stay on the page though…
Like I wish it was possible to do something like localstorage.setItem("key", JSON.stringify(items.value))
and then assign it to p.innerhtml
like p.innerhtml = JSON.parse(localstorage.getItem("key"))
so that the word values can stay on refresh, but I tried that and it didn’t seem to work. And then out all of that into a localstorage function, so that I can follow “state” as you stated.
Ah okay, gotcha. Would you have to add the created elements to the global scope since I’m using multiple functions, then? Because I’ve read that polluting the global scope isn’t good
This is interesting because I think I’m understanding about what your talking about with state. I formatted my code to what you described, and it appears that when I click the Submit button, it only creates the elements once and not multiple times
Data stored in LocalStorage is only accessible by the web page that stored it. The origin of a web page is determined by the combination of its protocol, domain, and port. For example, data stored on “https://example.com” will not be accessible by “https://example.net” or “http://example.com”, even if they are on the same domain.
LocalStorage is also available across browser sessions, meaning that the data stored in LocalStorage will persist even if the user closes the browser or navigates to a different website. This data remains available to the web page that stored it, even if the user returns to the website at a later time.
This makes LocalStorage useful for storing data that the web page needs to access even after the user closes the browser or navigates away from the website, such as user preferences or login information.
LocalStorage allows JavaScript and web applications to store data locally within the user’s browser, and it provides an API for storing and retrieving data. LocalStorage is a key-value store.
The LocalStorage API in JavaScript provides two main methods for storing and retrieving data:
- setItem(key, value) - This method is used to store a key-value pair in LocalStorage. The key and value are passed as arguments to the method.
Example:
localStorage.setItem("name", "John");
- getItem(key) - This method is used to retrieve a value from LocalStorage, based on the key. The key is passed as an argument to the method.
Example:
let name = localStorage.getItem("name");
console.log(name); // Output: "John"
Other methods include:
- removeItem(key) - Removes the key-value pair from the storage, based on the key passed as an argument.
- clear() - Removes all the key-value pairs from the storage.
- key(n) - Returns the key at the nth index in the storage.
- length - Returns the number of key-value pairs stored in the storage.
Note that LocalStorage has a storage limit of about 5-10 MB, depending on the browser and device.