Skip to content

Data management (tutorial)

Wouter edited this page Jun 27, 2020 · 29 revisions

In this tutorial I will show 3 different ways of storing data. (15 min read)

Author: Wouter van der Heijde - June 2020

For this tutorial I'll be using a node.js server and expect the reader to have at least some basic understanding of Javascript.

Different types of data require different methods of storing

Because not all the data is equally important to the owner of the webpage, you can choose the approach you find fitting to your needs. In this tutorial I tend to explain when it's best to use one of the three different approaches handled in this tutorial. Here is a heads up of the three different approaches i'll be explaining:

  1. Local storage (store data in the browser, personal data of the user)
  2. Server (store the data as a JSON file, usually done for small projects or prototypes)
  3. Database (best for large sets of data and multi user data-objects)

Local storage

What is local storage? Local storage is built-in web storage API that can be used to securely store data as key/value pairs.

When should I use this approach?

Lets say you have a form on your website but the form is rather long and your user doesn't feel like completing it in one turn. This is a perfect opportunity to use local storage. You can store the form data as key = form question and value = user's answer. Before you can store the data you need to parse the form data to a JSON format. This can be easily done using the javascript built-in FormData. Every time the user fills in an answer you can trigger the following function to parse the form into JSON-object.

const form = document.querySelector('#myForm') // first get acces to the form

form.addEventListener('change', function () {

    const formData = new FormData(form) // with form available we can parse the answers of the users into our formData object
    // the FormData object itself cannot be read or parsed so we'll have to take it apart

    let formDataObject = {} // define a Object you want the formData to be parsed to

    formData.forEach((value, key) => { // here we take all the values and keys in our formdata and assign it to the formDataObject
        formDataObject[key] = value
    })
    console.log(formDataObject) // now if we change something to the form we the output will be {firstName: "Wouter", lastName: ""}
    // this is perfect because we have a JSON-object containing all our form data

    // Now we can call the function to store our formDataObject with a matching local storage name
    setLocalStorage("formData", formDataObject)
})

Before you store the formData there are some things you need to know: * If you want to play around with these examples simply, clone this repo and you'll find a working example => example.1

Clone this wiki locally