From: Eduardo San Martin Morote Date: Fri, 1 Nov 2024 12:12:32 +0000 (+0100) Subject: docs: note about subscription flush X-Git-Tag: @pinia/nuxt@0.7.0~7 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=40828b652012ee8df822271c967a4e2c0636e928;p=thirdparty%2Fvuejs%2Fpinia.git docs: note about subscription flush Close vuejs/pinia#2819 --- diff --git a/packages/docs/core-concepts/state.md b/packages/docs/core-concepts/state.md index 8c6052bc..9c47bff6 100644 --- a/packages/docs/core-concepts/state.md +++ b/packages/docs/core-concepts/state.md @@ -252,6 +252,19 @@ cartStore.$subscribe((mutation, state) => { }) ``` +### Flush timing + +Under the hood, `$subscribe()` uses Vue's `watch()` function. You can pass the same options as you would with `watch()`. This is useful when you want to immediately trigger subscriptions after **each** state change: + +```ts{4} +cartStore.$subscribe((state) => { + // persist the whole state to the local storage whenever it changes + localStorage.setItem('cart', JSON.stringify(state)) +}, { flush: 'sync' }) +``` + +### Detaching subscriptions + By default, _state subscriptions_ are bound to the component where they are added (if the store is inside a component's `setup()`). Meaning, they will be automatically removed when the component is unmounted. If you also want to keep them after the component is unmounted, pass `{ detached: true }` as the second argument to _detach_ the _state subscription_ from the current component: ```vue