Local Storage Solutions

Warm Up

Discussions may vary; we would anticipate that most scholars will have some experience with apps that store information - social media in particular.

This is meant to serve as a hook for thinking of all the data that is stored!

Turn & Talk: Favorite App

Several questions are repeated from the Warm Up, which is intentional. This is meant to get students to think about client-side vs. server-side storage.

Turn & Talk: Local Storage

With any site opened in the browser, open the dev tools and in the console, type localStorage, then press enter/return.

What is the output? Is the output a number, string, array, or object? How do you know? What do you notice about all of the values in red?

  • The outputs students see will wildly vary site-to-site, and there is not necessarily a rhyme or reason. That’s good!
    • If there is nothing in localStorage, students will see this:
    • If there is data in localStorage, it might look somewhat like this:
  • The resulting output’s data type is an object. You can tell because of the curly braces around the output data.
  • The values in red are all in strings, or double quotes, even the arrays an objects (which is not the way we learned about arrays and objects!)

Do the same thing on a different site and compare the outputs - are they the same or different?

  • It is almost guaranteed that they will be different.

Try It: Get, Set, Remove and Clear

  1. localStorage.clear();
    • undefined
  2. localStorage.setItem('Karlie Kloss', 'Supermodel, Entrepreneur, Philanthropist');
    • undefined
  3. localStorage.getItem('Karlie Kloss');
    • “Supermodel, Entrepreneur, Philanthropist”
  4. Refresh the page.
  5. localStorage.getItem('Karlie Kloss');
    • still “Supermodel, Entrepreneur, Philanthropist”
  6. localStorage.removeItem('Karlie Kloss');
    • undefined
  7. localStorage.getItem('Karlie Kloss');
    • null
  8. localStorage.setItem("Kode With Klossy", "inspires!");
    • undefined
  9. localStorage.getItem("Kode With Klossy");
    • “inspires! “
  10. localStorage
    • Storage {Kode with Klossy: "inspires!",...};
  11. localStorage.clear();
    • undefined
  12. localStorage
    • Storage {length: 0};

Why do we get the outputs we do?

  • Anytime we get undefined, this is because that function does not return anything. .clear(), .setItem(), and .removeItem() take action, but don’t return anything to us.
  • When we call .getItem(), the return value is the value associated with the key that was passed in as an argument.
  • When we got null - that was because we tried to get a value of a key that does not exist. null is a value that represents a non-value. (Confusing, I agree, but the takeaway is that null means nothing is there.)
  • When we call localStorage, the return value is the Storage object of all the key/value data pairs that are currently in localStorage. The first time we do this, you can see the key/value pair ``Storage {Kode with Klossy: “inspires!”` returned, probably with some other pairs after. The second time, since we cleared localStorage, the object is empty and returns a length of 0.

CodePen

Make sure Dev Tools are open - type a name and click submit, you should see something like this:

> Storage {name: "Amy", length: 1}

Try It: Color Picker

Step 1: Copy and paste the code from each of the 3 files in this CodePen into a project called “color-picker” in Atom. It will be easier to see what’s happening when we run it in the real browser.

Step 2: Read through the JavaScript and make sure you understand how the current code is creating the functionality that the app currently has.

var newColor = $('.color-here');          // grab div from DOM & store in var
var changeColorBtn = $('.change-color');  // grab submit btn from DOM & store in var

changeColorBtn.on("click", changeColor);  // create event listener for button
                                          // when button is clicked, call changeColor func
function changeColor() {
  var color = $('.color').val();          // grab selected color from color input
  newColor.css('backgroundColor', color); // change CSS of div to that selected color
}

Step 3: With your partner, talk about/pseudo-code what code you would write, and where you would write it to implement localStorage.

You’ll probably hear them come to:

  • Inside the event handler, in addition to changing the CSS, we need to .setItem

This is a GREAT place for them to be at the end of this Try It/Turn & Talk. However, just that one change will not be enough. Class discussion notes explain.

Class Discussion

Bring the class together after Try It/Turn & Talk. Make sure that everyone is on board with the idea that inside the event handler, in addition to changing the CSS, we need to .setItem.

It’s recommended that you live code, or model here. Add the following as the last line of the event handler:

localStorage.setItem('color', color);

Use the input to select a new color, click submit. Call localStorage in the dev tools and show that the color is changed.

Now, refresh the page. The default color is back to black. If you check the dev tools, localStorage still has that last color.

Discussion:

  • If we have the color saved in localStorage, why isn’t it showing up when we load the page?
  • (See if you can get students to make progress on that question/be ready to lead them in the right direction.)
  • Answer: We set the color in localStorage, but when the page re-loads, we need to give directions to the app that when it loads, it needs to start with that color. If there wasn’t a color stored yet because it’s the first time this app is being used on the browser, we need to give it a default color.

Live Code: On line 3, below the newColor and changeColorBtn variables, declare a new variable.

var currentColor = localStorage.getItem('color') || "#000000";

This creates a new variable that will hold a hex code. If something is stored in localStorage with the key of color, it will get that. If that comes back as null, it’s empty, and it will default to black. We used the || - or operator.

newColor.css('backgroundColor', currentColor);

Here, before the event listener/handler is ever called, we will set the CSS to the color that was in localStorage or the default.

NOTE: This all happens “on page load” because it’s not written inside an event listener/handler. Any code written in what’s called the global scope will run as soon as the JavaScript is downloaded.

The file should now look like the CodePen below; make sure students have a chance to catch up and save that if they’d like.

See the Pen Try It: Color Picker Solution by Turing KWK (@turing-kwk) on CodePen.

Practice: localStorage

This repo has a solution; note that the same outcome can be written in many ways and this is just one way. Each addition from the original code was explained with comments about the respective line.