0

I want to check for the localStorage when at a page reload, if there is already an item there and if yes, I want to update "cryptocurreny" with the current values (title & value).

When I add something with my addCrypto() function, my localStorage looks like this:

[{"name":"ETH","value":"1.5"},{"name":"BTC","value":"2.75"}]

This is my component:

<template>
  <div>

    <div v-for="coin in cryptocurrency">
      <input v-model="coin.name">
      <input v-model="coin.value">
    </div>
    <button @click="addCrypto">
      New Cryptocurreny
    </button>

  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      cryptocurrency: [],
    }
  },
  methods: {
    set_data() {
      localStorage.setItem( 'cryptocurrencies', JSON.stringify(this.cryptocurrency) );
      this.cryptocurrency = this.get_data();
    },
    get_data(){
      return localStorage.getItem('cryptocurrencies');
    },
    addCrypto() {
      localStorage.setItem( 'cryptocurrencies', JSON.stringify(this.cryptocurrency) );
      this.cryptocurrency.push({ name: '', value: ''});
    }
  }
}
</script>

But I tried to add localStorage.getItem('cryptocurrencies'); at the end of my addCrypto() function but I get errors and at a page reload my cryptocurreny variable is empty.

2

1 Answer 1

1

I can't really work out what you're doing, but from what I see the set_data() function isn't called anywhere?

You'll want to use the mounted or created hook (see which one suits you) and do the check in there.

Example

mounted () {
  const saved = localStorage.getItem('cryptocurrencies')
  if (saved) {
    this.cryptocurrency = saved
  }
}

You could put that code into it's own method and call that in mounted() of course.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.