Skip to content

Commit f78f59e

Browse files
pguilbertposva
authored andcommitted
fix: throw when a store is used outside of a Nuxt-aware context.
Prefer the Nuxt Pinia instance over the global active Pinia instance. Since the Nuxt Pinia instance is discarded after each request, it ensures that we can't accidentally use one from another request. Additionally, `usePinia` will throw an error when used outside of a Nuxt-aware context. The error is as follows in dev : > [nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function.
1 parent a20f11e commit f78f59e

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<script lang="ts" setup>
2+
const useFancyCounter = async () => {
3+
await new Promise((resolve) => setTimeout(resolve, 0))
4+
5+
// ❌ bad usage: the use of a store after an await could lead to using the wrong pinia instance.
6+
return useCounter()
7+
}
8+
9+
const counter = await useFancyCounter()
10+
</script>
11+
12+
<template>
13+
<div>
14+
<p>Count: {{ counter.$state.count }}</p>
15+
<button @click="counter.increment()">+</button>
16+
</div>
17+
</template>

packages/nuxt/test/nuxt.spec.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,8 @@ describe('Nuxt', async () => {
3737
it('can auto import from layers', async () => {
3838
expect(await $fetch('/')).toContain('Layer store: 0')
3939
})
40+
41+
it('throws an error server-side when the nuxt context is not available', async () => {
42+
await expect($fetch('/usage-after-await')).rejects.toThrow()
43+
})
4044
})

0 commit comments

Comments
 (0)