Pinia w/ Vue3: Using Actions in template returns funcName is not a function
Asked Answered
T

3

8

Using a Pinia action from within the template in Vue3 gives

Uncaught TypeError: $setup.[storeName].[actionName] is not a function

Am I doing something wrong or is it expected behaviour. It doesn't seem that anybody else having the same issue. Google search didn't reveal anything.

I'm using the new components

Together answered 14/9, 2021 at 20:5 Comment(2)
Got the same issue. 1st time I've used piniaRepeat
Do control + R and should work. Can happen when the changes are not loaded upon saveCalender
E
7

I ran into this when I mistakenly tried to destructure actions as well as state and getters with storeToRefs, after not reading this bit from the Pinia docs carefully enough:

In order to extract properties from the store while keeping its reactivity, you need to use storeToRefs(). It will create refs for every reactive property. This is useful when you are only using state from the store but not calling any action. Note you can destructure actions directly from the store [emphasis added] as they are bound to the store itself too.

So given this template —

<template>
  <ul>
    <li v-for="thing in things" :key="thing">{{ frob(thing) }}</li>
  <li>
</template>

— and this store —

const useStore = defineStore("store", {
  state: () => ({ things: ["1", "2", "3"], }),
  actions: { frob(arg) { return `frobbed ${arg}`; } },
});
const store = useStore();

— if you try to destructure both things and frob with storeToRefs, you'll get TypeError: $setup.frob is not a function. Actions, unlike state and getters, should be destructured directly from the store object:

// wrong
const { things, frob } = storeToRefs(store);

// right
const { things } = storeToRefs(store)
const { frob } = store

Note that in Chrome the error will show up as Uncaught (in promise), while in Safari it will show up as Unhandled Promise Rejection.

Exterminatory answered 27/4, 2022 at 21:4 Comment(2)
You've enabled me to also not read the docs. I appreciate you and also you're an enabler of my disease.Chloropicrin
@Chloropicrin eh, nobody can be expected to read them cover to cover, or if they do to remember them.Exterminatory
F
5
const users = defineStore('users', {
  state,
  getters,
  actions,
})

some times using the same name for two stores causes this issue.

Foundry answered 2/6, 2023 at 10:2 Comment(1)
I encountered this situation when I set the same nameSeabury
N
0

Was also running into this, for me the fix was to check the structure of the store, e.g. all actions should be defined within the action brackets - obviously.

Nevertheless took me a while to figure this out, because stores can get complex and defining actions on the root level of a store will not raise any errors.

Neslund answered 5/1 at 9:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.