Search code examples
javascriptvuejs3pinia

How to migrate Vuex Method-Style Access to Pinia setup store


Pinia. In Setup Stores: ref()s become state properties, computed()s become getters, function()s become actions.

Vuex. Method-Style Access. You can also pass arguments to getters by returning a function. This is particularly useful when you want to query an array in the store:

getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}


store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

Not work

const getItemsByType = computed((element: string) => {
  return data.value[element] ? data.value[element] : []
})

That is like action but with return and also not help

  const getItemsByType = (element: string) => {
    return computed((element: string) => {
      return data.value[element] ? data.value[element] : []
    })
  }

That work, but that is an action and not getter(if consider that a getter is only with computed()) and is not cached

const getItemsByType = (element: string) => {
  return data.value[element] ? data.value[element] : []
}

Solution

  • Computed cannot have an argument.

    From Vuex docs:

    Note that getters accessed via methods will run each time you call them, and the result is not cached.

    So the Method-Style Access in Vuex is just a getter returning function. Equivalent in Pinia is to use plain function (last example)

    const getItemsByType = (element: string) => {
      return data.value[element] ? data.value[element] : []
    }