Home > Software engineering >  Vue: How to manipulate and use mappedState data?
Vue: How to manipulate and use mappedState data?

Time:10-13

I have a component that uses mapState to pull in 2 different states from the user store. In the user store, it makes a GQL call and gets a list of potentialNames. While it is awaiting that query, fetchingData is true and afterwards, it is set to false.

<template>
     <div v-if="firstTenNames>

     </div>

</template>

export default ({

     data: {
       return() {
          firstTenNames: [],
       }
     },
     computed: {
         ...mapState('user', ['potentialNames', 'fetchingData']),
     }
});

I want to be able to know as soon as the data is fetched and potentialNames has a value so that I can splice off the first 10 names and set it to firstTenNames. Is there a non-expensive way of doing this? I was thinking of watching the property but is that the only way? Also, can you even watch it if it's a store property?

CodePudding user response:

The solution is to turn firstTenNames into a computed property

<script>
export default {
  computed: {
    ...mapState(['potentialNames', 'fetchingData']),

    // whenever `potentialNames` changes
    // this property is automatically recomputed
    firstTenNames() {
      // could be `null`, depending on your code
      if (this.potentialNames) {
        return this.poentialNames.slice(0, 10)
      }
      return []
    }
  }
}
</script>

firtTenNames is computed only based on another state (potentialNames). In that kind of situation, it's much easier to use a computed property that will make sure things are automatically in sync.

Yes, you can achieve the same by storing firstTenNames in data and adding a watcher for potentialNames. This is just more work and is error-prone especially if your state depends on multiple other values (e.g., you could easily forget to add some watchers).

There are some cases where using a watcher is actually needed (see https://vuejs.org/v2/guide/computed.html#Watchers). However, in most cases, computed properties are more appropriate.

  • Related