Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Counter 'localStorage'

in this counter i want to save number in localStorage, tell me what is the error why it is not saved in memory

const app = Vue.createApp({
  data() {
    return {
      counter: 0,
    };
  },
  methods: {
    getItem() {
      localStorage.setItem('count', this.counter);
      return localStorage.getItem('count');
    },
  },
}).mount('#app');
  <div id="app">
      <h2>{{getItem()}}</h2>
      <button @click="counter--">-</button>
      <button @click="counter++">+</button>
    </div>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The problem here is whenever the page loads, and you call getItem() you reset localStorage.count = 0 since it automatically initializes to 0.

Instead, do something like this:

const app = Vue.createApp({
  data() {
    return {
      counter: localStorage.getItem('count') || 0,
    };
  },
  watch: {
    counter() {
      localStorage.setItem('count', this.counter);
    }

  },
  methods: {
    getItem() {
      return localStorage.getItem('count');
    },
  },
}).mount('#app');

This way, you’re setting the initial value to the value from storage; and watching that value for a change and then updating localStorage to reflect the correct value stored across the window.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading