N
Nuxtβ€’6mo ago
ParadoX

How to create a stateful composable that uses useState?

So I am refactoring my app and I am replacing pinia stores with composables. If I want a global state that is shared with all instances of that composable, I need to define this ref outside of the exported function. Like this:
const globalState = ref();
export default () => {
// [...]
return {
// [...]
state: readonly(globalState),
};
}
const globalState = ref();
export default () => {
// [...]
return {
// [...]
state: readonly(globalState),
};
}
However, if I want to use useState, I cannot do that outside of the composable function. What now? πŸ€”
5 Replies
ParadoX
ParadoXOPβ€’6mo ago
Bonus question: Inside my composable useSearch that exports a function that returns this:
const fetchResults = () => useAsyncData(() => $fetch([...]))
const fetchResults = () => useAsyncData(() => $fetch([...]))
Somewhere else I might use it like that:
const { fetchResults } = useSearch();
const { data, pending, status, error} = await fetchResults();
const { fetchResults } = useSearch();
const { data, pending, status, error} = await fetchResults();
Is there a way of accessing data, pending, status and error inside the composable itself? πŸ€” I need those to be part of the gobale state
Cake
Cakeβ€’6mo ago
// /composables/foo.ts

export const useFoo = () => {
const foo = useState('foo', ...)

return {
foo
}
}
// /composables/foo.ts

export const useFoo = () => {
const foo = useState('foo', ...)

return {
foo
}
}
foo here would be global in this example u're using a composable inside a function, not top level, which is where composables should be called/used u can instead use $fetch directly and implement the loading/error states in a try/catch/finally block
ParadoX
ParadoXOPβ€’6mo ago
But I want to use useAsyncData because of SSR. In order to avoid double requests πŸ€”
ParadoX
ParadoXOPβ€’6mo ago
Medium
Handle Global State management in Nuxt3
Developers usually follow the principle not to expose state in areas where it is not needed. In order to keep this principle intact, we…
ParadoX
ParadoXOPβ€’6mo ago
But it feels a bit wonky to pass the results back to the composable after calling it from outside πŸ€”

Did you find this page helpful?