-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: throw when a store is used outside of a Nuxt-aware context. (POC)
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.
- Loading branch information
Showing
3 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
<script lang="ts" setup> | ||
const useFancyCounter = async () => { | ||
await new Promise((resolve) => setTimeout(resolve, 0)) | ||
// ❌ bad usage: the use of a store after an await could lead to using the wrong pinia instance. | ||
return useCounter() | ||
} | ||
const counter = await useFancyCounter() | ||
</script> | ||
|
||
<template> | ||
<div> | ||
<p>Count: {{ counter.$state.count }}</p> | ||
<button @click="counter.increment()">+</button> | ||
</div> | ||
</template> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,27 @@ | ||
import { useNuxtApp } from '#app' | ||
import { | ||
defineStore as _defineStore, | ||
type Pinia, | ||
type StoreGeneric, | ||
} from 'pinia' | ||
export * from 'pinia' | ||
|
||
export const usePinia = () => useNuxtApp().$pinia | ||
|
||
export const defineStore = (...args) => { | ||
if (!import.meta.server) { | ||
return _defineStore(...args) | ||
} | ||
|
||
const store = _defineStore(...args) | ||
|
||
function useStore(pinia?: Pinia | null, hot?: StoreGeneric): StoreGeneric { | ||
if (pinia) { | ||
return store(pinia, hot) | ||
} | ||
|
||
return store(usePinia(), hot) | ||
} | ||
|
||
return useStore | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters