w3bdesign / nuxtjs-woocommerce

⚡️ Nuxt 3 and Vue 3 headless eCommerce site with WooCommerce backend and Algolia search

Home Page:https://nuxt.dfweb.no

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Pinia side effect

w3bdesign opened this issue · comments

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) }) } }