Search code examples
vue.jspinia

Is it possible to use $subscribe or watch inside the store itself?


I want to watch the store and make a new api call (use store action) each time when a part of the store changes. How can I implement this watcher inside the (defineStore()) store itself ?


Solution

  • If you use a setup store, you could use this syntax. This would watch just one state property, then trigger a side effect based on that state property changing:

    import { defineStore } from "pinia";
    import { ref, watch } from "vue";
    
    export const useCartStore = defineStore("cart", () => {
        // state
        const items = ref([]);
        let cartIsEmpty = ref(false);
    
        // actions
        function emptyCart() {
            // *logic here to empty the cart*
            cartIsEmpty.value = true;
        }
    
        // watch
        watch(cartIsEmpty, ()=> {
            if (cartIsEmpty.value === true) {
                fetchItems();
            }
        });
    });