B
B
Bogdan2018-02-17 22:23:22
Vue.js
Bogdan, 2018-02-17 22:23:22

Getter caching with arguments?

Hello. Could you tell. I use getter function

checkTodo: ( state ) => (id) => {
      console.log( 'checkTodo', id )
      return state.todos.find(todo => todo.id===id ).done
    }

It turns out that it recalculates its value every time the value in the array changes, for example, the value only for id = 1 has changed, the call will go for other values, as can be seen in the example. Is there some kind of caching option? Thanks
Here's what the documentation says:
Like computed properties, getter results are cached based on their dependencies and will only be recalculated when one of its dependencies changes.

Example on codepen
import Vuex from 'vuex'
import { mapGetters, mapMutations } from 'vuex'

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: 'First', done: true },
      { id: 2, text: 'Second', done: false },
      { id: 3, text: 'Thirh', done: false }
    ]
  },
  getters: {
    allTodos( state ) { return state.todos },
    checkTodo1( state ) {
      console.log( 'checkTodo  1' )
      return state.todos.find(todo => todo.id===1).done
    },
    checkTodo: ( state ) => (id) => {
      console.log( 'checkTodo', id )
      return state.todos.find(todo => todo.id===id ).done
    }
  },
  mutations: {
    toggleDone( state, id ) {
      const todo = state.todos.find(el => el.id === id );
      todo.done = !todo.done;
    }
  }
})

new Vue({
  el: '#app',
  store,
  template: `
    <ul>
      <li v-for='todo in allTodos'>
      {{ checkTodo(todo.id) }}
        <button @click='toggleDone(todo.id)'>
          {{todo.text}}
        </button>
      </li>
      <li> {{checkTodo1 }}</li>
    </ul>`,
  computed: {
   ... mapGetters(['allTodos', 'checkTodo', 'checkTodo1'])
  },
  methods: {
    ...mapMutations(['toggleDone'])
  }
})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Wells, 2018-02-18
@Alex_Wells

state.todos changes, so it makes sense that all setters are updated. It is right.
Most likely, there is no caching method for such cases, and it is not really necessary)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question