Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
Let's get some hands-on experience using Local Storage in a small demonstration app.
Work along with the video:
You can launch the workspace for this video to follow along.
If you would prefer to download and work from a local copy instead:
- Download and unzip the project file here or from the Downloads tab.
- Make sure you have nodemon installed. To install, run
npm install -g nodemon
from the command line. - Inside the project folder, open the folder called Start from the command line, then run
npm install && nodemon
- You can now navigate to
localhost:3000
in a browser to view the project. - To view the finished project, you can complete step 3 & 4 from the Finished_Project folder instead of the Start folder.
-
0:00
We've seen how to work with local storage on its own in the console.
-
0:04
But what is it like to integrate it into a project?
-
0:07
For this project, we'll save recent searches made on a page and
-
0:10
display them in a list on the screen.
-
0:13
This will quickly give you a chance to see local storage in action.
-
0:17
You can launch the workspace to follow along or
-
0:19
download the files from this page to use your own text editor.
-
0:23
Let's take a look at what we'll build together.
-
0:26
Here's a generic search bar.
-
0:28
It could belong to any web page.
-
0:30
When I submit searches to it They appear below.
-
0:40
They're also inserted into local storage.
-
0:44
Now submit one more search.
-
0:48
And then I'll close the window.
-
0:55
Now when I reopen the page, the words are still there.
-
0:59
Now if I click the Clear Storage button.
-
1:02
They disappear, and the searches are removed from local storage.
-
1:07
In this video, we'll write the code that save searches to local storage,
-
1:10
maintains this visible list in the UI,
-
1:12
and clears the store when this clear button is pressed.
-
1:17
Let's switch over to the code and have a look.
-
1:22
Here you can see that we have a very simple HTML web page.
-
1:27
We have a form with an input and a submit button.
-
1:34
We also have our clear button that we already saw in use.
-
1:39
I've already added some JavaScript that takes care of listening for
-
1:42
events as well as manipulating the DOM.
-
1:44
When the page loads, these two events are set up.
-
1:50
One fires for form submissions and
-
1:52
the other fires when the Clear button is clicked.
-
1:55
When a form is submitted this handler attempts to store the string and
-
1:59
updates the list on the web page.
-
2:04
When the clear storage button is clicked, this handler deletes all the searches
-
2:08
from storage that updates the UI on the page.
-
2:13
I've written a couple of helper functions to update the UI.
-
2:16
This one creates a new list item and
-
2:19
adds it to the bottom of the unordered list element.
-
2:23
And this one simply resets the list by emptying the HTML inside.
-
2:31
Finally, I will establish some shell functions that we'll be writing together.
-
2:35
You can see these functions are called in the code below.
-
2:46
So what we need to do is connect these functions to local storage and
-
2:50
serve the results.
-
2:51
Now before we do all that.
-
2:53
Let's make sure we can even use local storage at all.
-
2:57
We'll start by wrapping the contents of the onLoad function in an if block.
-
3:06
Inside of the if statement, we'll execute
-
3:11
a function called supportsLocalStorage.
-
3:15
And if supportsLocalStorage returns True,
-
3:22
then we wanna do all this, awesome.
-
3:27
There we go.
-
3:28
Now let's fill out the supports local storage function.
-
3:33
Now what we're really doing is testing that the browser has access to an object
-
3:38
called local storage.
-
3:45
And we're gonna test that a key called
-
3:51
localStorage exists in the window and.
-
4:05
That it's not null.
-
4:11
So this is saying, make sure the window object has a localStorage key and
-
4:18
make sure that localStorage key is a set of functions or
-
4:23
properties but that it's not null.
-
4:28
Now in some browsers or in some devices, this could throw an error.
-
4:32
So rather than trying to run this and flooding the console with errors.
-
4:40
Let's wrap this in a try catch block.
-
4:44
So we'll try that.
-
4:49
Oops, some Python was slipping in there.
-
4:53
We'll catch any exceptions.
-
4:57
If there's an exception, we'll return false.
-
5:03
Don't wanna forget my semicolon.
-
5:06
Now let's walk back through our onLoad function and
-
5:08
complete the code we'll need as we encounter it.
-
5:13
Here's our initiation code, which sets up our web page.
-
5:18
And here in the initialization code we're going to update the UI
-
5:22
with any searches that were already done.
-
5:26
We'll need to retrieve those searches from localStorage.
-
5:29
And that work is going to be done by the getRecentSearches function.
-
5:34
So, let's write the getRecentSearches function now.
-
5:38
First, we're going to retrieve our list from localStorage.
-
5:48
LocalStorage.getItem('recentSearches').
-
5:57
And that's being assigned to the variable searches.
-
6:01
Now keep in mind that this value is going to be a string
-
6:06
even though we're going to store our searches as an array.
-
6:09
That's because local storage can only store string types, and
-
6:13
this presents only a minor challenge.
-
6:14
The way we'll work around it is to store all of our data as stringified JSON.
-
6:19
I'll show you how to do that in just a moment.
-
6:21
For now just know that when we get data from recent searches in localStorage,
-
6:26
we're going to have to parse it to return an array.
-
6:29
We also have to take into account the fact that the string may be empty.
-
6:33
So we'll need to test searches to see if it is truthy, meaning if it exists and
-
6:38
has a length.
-
6:40
If it is truthy, we'll parse the string into an array and
-
6:43
return it using JSON.parse.
-
6:45
All of that sounds complicated, but
-
6:48
we're going to accomplish it in a few lines of code.
-
7:00
If searches exist, we're
-
7:05
going to return it after turning
-
7:10
it into a valid JSON object.
-
7:23
Otherwise let's return an empty array.
-
7:29
As we saw, this function returns an array to the onload function.
-
7:38
The results are then iterated over and
-
7:41
placed on the page using the appendListItem method.
-
7:47
Now let's consider the submit event.
-
7:50
When a user enters some text and hits return or click Submit, this handler calls
-
7:55
a function named saveSearchString.
-
8:00
Notice this takes place inside of an if condition.
-
8:03
That's because apart from saving the search string,
-
8:06
it's also doing some validation.
-
8:08
If the submission is valid, it will save and return true.
-
8:12
Otherwise it will not save and return false.
-
8:16
So let's go up to saveSearchString,
-
8:18
decide which search strings are going to be valid.
-
8:23
Let's accept any unique entries whose lengths are greater than 0.
-
8:28
To know if we've already saved the string to local storage, and
-
8:31
therefore it's not unique, we'll need to pull all the strings out to examine them.
-
8:35
We've already written a function to get those strings, so let's call it and
-
8:39
assign the result to the variable searches.
-
8:46
Now let's first test whether the string is truthy or not,
-
8:49
then look to see if it's a duplicate of what has already been stored.
-
8:53
If either of these checks fail,
-
8:55
we'll exit out of the handler without doing anything with the submission.
-
9:01
Remember this takes a string variable.
-
9:04
So, we'll say if String is not truthy,
-
9:11
Or If the string
-
9:20
Already exists inside of the searches
-
9:26
array, we'll return False.
-
9:46
Otherwise we push the string to our searches array.
-
9:58
Now, we'll store our searches under
-
10:03
the recentSearches key in localStorage.
-
10:08
Remember, we're going to use the stringify method.
-
10:15
To turn our JSON object into a string.
-
10:20
Finally, since we've done our validation, we know we can return true here.
-
10:29
Going back to our onload block.
-
10:32
We are inside the submit event, so this all evaluated to true.
-
10:37
Now we're going to update the UI by appending the search term to the list.
-
10:47
Finally we need to be able to remove our searches using the clear button.
-
10:55
The removeSearches function is quite crude and really only needs one line of code.
-
11:07
We're going to remove recentSearches from our localStorage all together.
-
11:16
Now we could have done this,
-
11:18
from inside the onload function all the way down here.
-
11:23
You could replace this line of code with this one.
-
11:29
But most cases, it's going to be better to pull it out.
-
11:33
One of the advantages to this is that all of our references to localStorage
-
11:37
are in one place and in these functions here.
-
11:43
This means that if we ever wanted to use a different storage for these, take for
-
11:47
instance a database, we could just change these functions without having to
-
11:51
dig into other parts of our code.
-
11:53
And this is the end of our project.
-
11:55
Let's test in the browser to make sure it all works.
-
12:09
Oops.
-
12:10
It looks like there's an error with our code.
-
12:13
So let's go back and see what we can find.
-
12:19
There it is here in the saveSaveString function.
-
12:23
I'm saving only the single string that was provided
-
12:28
in that search rather than storing our entire searches array.
-
12:38
So here I'll replace strings, string rather with searches.
-
12:48
Now let's refresh the page.
-
13:00
Now we can see that our application is working.
-
13:05
Well done.
-
13:06
Now you can use localStorage to store data, right inside the browser.
-
13:10
Congratulations and keep up the great work.
You need to sign up for Treehouse in order to download course files.
Sign up