From: Eduardo San Martin Morote Date: Thu, 16 Feb 2023 09:19:28 +0000 (+0100) Subject: docs: note about useStores within actions X-Git-Tag: @pinia/nuxt@0.4.7~4 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=dab114bf2d440256b5d179eee028a36374d6ea17;p=thirdparty%2Fvuejs%2Fpinia.git docs: note about useStores within actions See #2004 --- diff --git a/packages/docs/cookbook/composing-stores.md b/packages/docs/cookbook/composing-stores.md index 2100c5cc..fd3e7eca 100644 --- a/packages/docs/cookbook/composing-stores.md +++ b/packages/docs/cookbook/composing-stores.md @@ -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) + } + }, + }, +}) +```