]> git.ipfire.org Git - thirdparty/vuejs/pinia.git/commitdiff
docs: note about useStores within actions
authorEduardo San Martin Morote <posva@users.noreply.github.com>
Thu, 16 Feb 2023 09:19:28 +0000 (10:19 +0100)
committerGitHub <noreply@github.com>
Thu, 16 Feb 2023 09:19:28 +0000 (10:19 +0100)
See #2004

packages/docs/cookbook/composing-stores.md

index 2100c5cc0a4cfb2c4a2c877b0f45a98d1d40eb54..fd3e7eca291a0dc3ad902f5390d79296318e9ff6 100644 (file)
@@ -107,3 +107,29 @@ export const useCartStore = defineStore('cart', {
   },
 })
 ```
+
+Since actions can be asynchronous, make sure **all of your `useStore()` calls appear before any `await`**. Otherwise, this could lead to using the wrong pinia instance _in SSR apps_:
+
+```js{7-8,11-13}
+import { defineStore } from 'pinia'
+import { useUserStore } from './user'
+
+export const useCartStore = defineStore('cart', {
+  actions: {
+    async orderCart() {
+      // ✅ call at the top of the action before any `await`
+      const user = useUserStore()
+
+      try {
+        await apiOrderCart(user.token, this.items)
+        // ❌ called after an `await` statement
+        const otherStore = useOtherStore()
+        // another action
+        this.emptyCart()
+      } catch (err) {
+        displayError(err)
+      }
+    },
+  },
+})
+```