w3bdesign / nuxtjs-woocommerce

⚡️ Nuxt 3 and Vue 3 headless eCommerce site with WooCommerce backend and Algolia search
https://nuxt.dfweb.no
GNU Affero General Public License v3.0
194 stars 45 forks source link

Pinia side effect #1285

Open w3bdesign opened 6 months ago

w3bdesign commented 6 months ago

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) }) } }
w3bdesign commented 6 months ago

https://github.com/w3bdesign/nuxtjs-woocommerce/blob/13d5a9d1eddacfbb47989f82bf269e650b530e8c/components/Layout/LayoutCart.vue