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:
However, if I want to use useState, I cannot do that outside of the composable function. What now? π€
5 Replies
Bonus question: Inside my composable useSearch that exports a function that returns this:
Somewhere else I might use it like that:
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
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
blockBut I want to use useAsyncData because of SSR.
In order to avoid double requests π€
I'll try this approach: https://medium.com/@cybercoder.naj/handle-global-state-management-in-nuxt3-468e5b3e7901
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β¦
But it feels a bit wonky to pass the results back to the composable after calling it from outside π€