Skip to content
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

Pinia side effect #1285

Open
w3bdesign opened this issue Mar 16, 2024 · 1 comment
Open

Pinia side effect #1285

w3bdesign opened this issue Mar 16, 2024 · 1 comment
Assignees

Comments

@w3bdesign
Copy link
Owner

Subscribing Side Effects on Store Changes One significant advantage of Pinia is the ability to extend the store’s functionalities and implement side effects using plugins. With this ability, we can easily subscribe to changes in all the stores or in a specific store to perform additional actions like synchronizing data with the server when needed. Take the following cartPlugin, for instance:

//main.ts import { cartPlugin } from '@/plugins/cartPlugin' //... const pinia = createPinia() pinia.use(cartPlugin) app.use(pinia) //... The cartPlugin is a function that receives an object containing a reference to the app instance, the pinia instance, the store instance, and an options object. Vue will trigger this function once for every store in our application. To make sure we are subscribing only to the cart store, we can check the store’s id (see Example 9-17). Example 9-17. Cart plugin //src/plugins/cartPlugin.ts export const cartPlugin = ({ store}) => { if (store.$id === 'cart') { //... } } Then we can subscribe to the cart store changes using the store.$subscribe method, as in Example 9-18. Example 9-18. Cart plugin subscribing to store changes //src/plugins/cartPlugin.ts export const cartPlugin = ({ store}) => { if (store.$id === 'cart') { store.$subscribe((options) => { console.log('cart changed', options) }) } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

When branches are created from issues, their pull requests are automatically linked.

1 participant