How to set and get data from local-storage
Today we’ll learn how to set data and get data from local storage in a very easy way
You can read this article on Medium
So let’s do it
To get a better understanding of how to set data and get data from local storage Open your favorite code editor and create three files:?index.html,?index.js,?or (if you want)?index.css.
We are basically going to make a simple to-do app. I know it’s very common, but it will help us to get a good understanding of local storage.
# Index.html
This is our HTML code. we have 2 inputs one for the title one for the description and submit button.
let’s also add the bottom section for displaying the task.
Now, let’s move to the main topic i.e. Local-storage.
# Index.js
Get all the elements in your index.js
Define an empty array
Let’s add an event listener to the submit button
Here we’ve added the click event to the submit button
When the user clicks on the submit button, it will create an object that store the title input value and the description input value. check your console you will get the object.
领英推荐
In line no 8, we’re checking if anything is stored in the localStorage that has the key?allTask,?store it in a variable.
As we know, we haven’t set anything to the local storage yet, so it’ll be null.
In line no. 10, we’re checking if local storage is present, which means it’s not null or undefined.
Then set all the existing tasks that are in local storage, which are now stored in the variable named?fetchTaskFromLS?, and the new task created by the user to the taskArray. (it will run each time if local storage in not null)
But in the else condition if?fetchTaskFromLS?is null. Then push the new task to the taskArray (It will run if you have not added the task to the local storage or if the page renders for the very first time. After adding the task to the local storage, it will not run in this else condition because local storage is not null or even if you reload your page because local storage does not clear when the page session ends.)
In line no. 15, now we are setting each time updated taskArray to the local storage with the key name of?alltask.
After that, we’re calling a function displayTask() and setting the input value to the empty string so that after adding the task, the user will no longer see the filled input.
Let’s define the displayTASK function
First, get the task from local storage and stored it in the variable name?getTaskFromLocalStorage?if local storage is empty there is no task then set?getTaskFromLocalStorage?to the empty array (otherwise it will throw an error )
After that, we’re displaying the task inside the bottom-section
So, we’re mapping over the task and returning the HTML for each task.
We have to call this function when the window is loaded so that if there is any task in the local storage it will display in the browser.
Hope you like it ??
Happy coding!
want to give suggestions:-
have a look at?my portfolio
Email me at [email protected]