-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
In-store setup #903
Comments
This is actually already supported with the setup syntax: export const useStore = defineStore('store', () => {
const start = ref(null)
// ...
async function fetchRoute() {
// fetch route
}
watchEffect(() => {
if (start.value && destination.value) {
fetchRoute()
}
})
return { start, destination }
}
}) There is currently only one example of this in docs: https://pinia.esm.dev/introduction.html#basic-example and it's tracked at #829 to add more |
@posva Is there a way to use the setup syntax to listen for whole-state changes cf. |
No, You can simply use a watcher |
Passing an explicit list of watch([start, destination, route], ([newStart, newDestination, newRoute]) => {
// ...
}) Or is there anything simpler / less repetitive? Would something like this work? const storeDef = { start, destination, route }
watch(reactive(storeDef), (v, _) => {
// do something with v.start etc.
})
return storeDef |
What problem is this solving
Sometimes i need to react to changes to the state in a more granular way that is completely decoupled from the component that uses the store. For example, consider this simple use case:
Whenever start or destination changes, i want to fetch a new route, e.g.
There is currently no option to put this in the store directly. So i either have to pick a component to include the watcher or put it in
app.ts
where the store is created.Proposed solution
Add a
setup()
like method to the store where i can put watchers and other initialization logic.e.g.
Describe alternatives you've considered
$subscribe
:The text was updated successfully, but these errors were encountered: