Skip to content

Instantly share code, notes, and snippets.

@khalidwilliams
Last active July 16, 2019 17:52
Show Gist options
  • Save khalidwilliams/edbfc87f3d524340ffdc8d2ce573bfed to your computer and use it in GitHub Desktop.
Save khalidwilliams/edbfc87f3d524340ffdc8d2ce573bfed to your computer and use it in GitHub Desktop.
1904 JSON / localStorage Review

JSON and Local Storage Review

It's important to remember why we use JSON and localStorage -- formatting and saving data on the user's computer, via the WebStorage API.

Using localStorage

localStorage gives us access to a storage object in the browser (go ahead and try calling localStorage in the console. We get an object back!)

This object gives us access to a few methods, such as:

  • localStorage.setItem([key],[value]) => undefined
  • localStorage.getItem([key]) => "[value]" (as a string)
  • localStorage.removeItem([key]) => undefined
  • localStorage.clear() => undefined

We can also examine storage via the Application tab in the dev tools!

On its own, localStorage can easily store primitive data types. This includes:

  • Strings
  • Booleans
  • Numbers
  • null
  • undefined

It's important to note that keys must be strings. After saving our values to localStorage, storedValues will be converted to strings.

In order to convert values back to their original data type, as well as store complex data types, we use:

JSON

JSON gives us access to the [JSON object] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON) (try it in the console!)

The object only has two methods we're intersted in:

  • JSON.stringify(data) => valid JSON string
  • JSON.parse(valid JSON string) => original data form

These methods will create strings that follow JSON rules, and parse valid JSON strings. Something being parsed must follow JSON rules

By default, the output of these methods DOES NOT get put into storage. We have to do that ourselves:

// Examine the storage object in the console 

var myInfo = {name: 'Khalid', hometown: 'Carrboro, NC', isHungry: true}
var strInfo = JSON.stringify(myInfo)

// Examine the storage object again. Nothing's changed! 

localStorage.setItem('regKhalid', myInfo)

// Examine the storage object. This is why we need to stringify complex data

localStorage.setItem('strKhalid', strInfo)

// Examine the storage object again. See the difference?

Modifying / Updating localStorage

So we've saved some info. However, I'm no longer hungry. How can we update our saved object to reflect my new state?

In order to change data in localStorage, we have to:

  1. Retrieve it
  2. Parse it / modify it
  3. Stringify it (if the data is complex)
  4. Store it again
// Let's get our data back
var uselessKhalid = localStorage.getItem('regKhalid')
var usefulKhalid = localStorage.getItem('strKhalid')

// Let's parse it

var uneditableKhalid = JSON.parse(uselessKhalid)
var editableKhalid = JSON.parse(usefulKhalid)

// uneditableKhalid is uneditable. Why?

// Let's edit editableKhalid 

editableKhalid.isHungry = false; // How else could we write this statement?

// Let's save the new and satiated Khalid 

var satiatedKhalid = JSON.stringify(editableKhalid);
localStorage.setItem('strKhalid', satiatedKhalid);

// regKhalid wasn't very helpful. How can we remove it from storage?

Data Attributes

Let's take a look at our definition of data-attrbiutes from yesterday:

  • a way of storing information related to the data model on an html element

This is a helpful defintion for thinking about data attributes with regards to Turing projects. But the true defition is a litle more robust.

From the HTML docs:

Custom data attributes are intended to store custom data, state, annotations, and similar, private to the page or application, for which there are no more appropriate attributes or elements

This means they are useable for any situation when we need custom information or attributes, and an existing arttribute won't do the trick. They are meant to be used in conjunction with classes and ids, not to replace them. There are situations where a custom data attribute may be more appropriate than a class, which is typically meant to be used for applying styling. While ids are appropriate identifying attributes, when we want to have an identifier on the DOM that is meant to match an identifier in our data model / localStorage, data-attributes may be a more appropriate choice.

Uses I have seen include:

  • Hotkeys
  • Custom styling
  • Identifiers
  • Distance-based data
  • Numerical data (song lengths, file size, image size)
  • Dealing with metadata
  • Tooltips
  • Search and sort functionality

Essentially it's a way to add extra functionality for developers in our apps / webpages.

A note: data-attributes may not be accessilbe by assitive technology, so it's good to use them for non-essential / private data

Let's look at the syntax for how to access them: https://codepen.io/khalidwilliams/pen/NVwvoK?editors=1111

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment