0

I'm saving an array into local storage

and adding/removing from the array like.

I want the count of the array to update in the component as and when new items get added to the array in localstorage

I am using a computed property:

 numOfCodes: {
      // getter
      get: function() {
        let storageItems = localStorage.getItem("items");
        if (storageItems) {
          var items = JSON.parse(storageItems);
          return items.length;
        }
        return 0;
      }
    }

The count is not changing as expected. it remains the same.

I have tried using vuex, but still have the issue. the goal is having the value react to the localstorage change

raklos
  • 28,027
  • 60
  • 183
  • 301

3 Answers3

0

The localStorage does not share the reactivity system of Vue. This whole process is handled by Vue itself. See also here. I think you should be able to manually trigger a re-render by forcing Vue to update all of its components using forceUpdate. However, keep in mind that you would have to trigger the re-render whenever you update the localStorage or whenever you expect it to be updated.

tony19
  • 125,647
  • 18
  • 229
  • 307
Aer0
  • 3,792
  • 17
  • 33
0

I think a solution to this would be to use vuex, I've mocked up an example below:

On your component:

computed: {
    ...mapGetters({
        itemsCount: 'mockLocalStorage/itemsCount'
    })
},

created() {
    this.setItems(...);
},

methods: {
   ...mapActions({
       setItems: 'mockLocalStorage/setItems'
   })
}

In vuex:

state = {
    items: []
};

getters = {
    itemsCount: state => state.items.length
};

actions: {
    setItems({ commit }, items) {
        localStorage.setItem('items', items);
        commit('setItems', items);
    }
};

this.itemsCount would then be reactive in your component, and you could create a few more actions to add and remove individual items.

Rich
  • 512
  • 3
  • 11
-1

Use a watcher.

props: ['storageItems', 'itemsLength'],
watch: {
    storageItems: function(newVal, oldVal) {
        this.storageItems = newVal
        this.itemsLength = newVal.length
    }
}
tony19
  • 125,647
  • 18
  • 229
  • 307
ImRajdeepB
  • 67
  • 1
  • 11