In the previous lesson, we added a form to insert a new category.

However, when we reload the page, we’re presented that form again, because the category was not persisted anywhere.

Let’s do it, and save the category to local storage.

Tip: if you are unfamiliar with local storage, check this article I wrote about it.

How do we do that? We use a watcher.

A watcher is a function that’s triggered when a specific property of the state, or a computed property, changes its value.

Let’s add it to App.vue:

//...
export default {
  name: 'app',
  //...
  watch: {
    categories() {
      localStorage.setItem('categories', JSON.stringify(this.categories))
    }
  }
}

In addition to storing the data, we also need to retrieve it when the application starts.

To do that, we attach a function to the mounted property of our component, that checks if the local storage contains the categories property, and we parse it from JSON.

Based on what we find we set the shouldShowAddCategory state property which we use to determine if the AddCategory component should show.

<script>
//...
export default {
  //...
  mounted() {
    if (localStorage.getItem('categories')) {
      this.categories = JSON.parse(localStorage.getItem('categories'))
    }

    if (!this.categories.length) {
      this.shouldShowAddCategory = true
    }
  }
}
</script>

Now when adding a category and then you reload the app, you won’t see the AddCategory component anymore, unless you clear the local storage manually using the console, using this line of JavaScript:

localStorage.setItem('categories', '')

See the app in the current state on CodeSandbox.


Go to the next lesson