Search code examples
vue.jsnuxt.jslocal-storage

Accessing local storage in computed property


I'm trying to record some user preferences in the local storage for ease of use of my website. I wrote this code and it seems to work.

<template>
    <v-data-table
      //... item binds etc
      :items-per-page="itemsPerPage"
      @update:items-per-page="itemsPerPageUpdated"
    >
</template>

<script>
  // ...
  data: () => ({
    // ...
    _itemsPerPage: 10,
  }),

  computed: {
    itemsPerPage() {
      this._itemsPerPage = localStorage.getItem("itemsPerPageDevice") || 10
      return parseInt(this._itemsPerPage, 10)
    },
    // ...
  methods: {
    itemsPerPageUpdated(val){
      this._itemsPerPage = val;
      localStorage.setItem("itemsPerPageDevice", val);
    },

  },

</script>

But I'm not sure where the computed properties fall in the nuxt life cycle. I had an error in the docker environment that said "localStorage not defined" but never had this error outside of docker.

My questions is, is it okey to access the localStorage in computed properties in nuxt?


Solution

  • it is ok but only in client side so you need to check process.client before using localStorage:

    computed: {
        itemsPerPage() {
          if (process.client) {
            this._itemsPerPage = localStorage.getItem("itemsPerPageDevice") || 10
            return parseInt(this._itemsPerPage, 10)
          } else {
            return 10
          }
        },
    }