I have a following code for the template:
<script setup>
import {useProductStore} from "@/store/products";
import {ref} from "vue";
import {storeToRefs} from "pinia";
const productStore = useProductStore()
let { products } = storeToRefs(productStore)
let { categories } = storeToRefs(productStore)
const { showProducts } = productStore
</script>
<template>
<div>
<div class="row">
<div class="col-md-2">
<button class="d-block w-100"
@click="showProducts('all')">All</button>
<button class="d-block w-100"
@click="showProducts(category.id)"
:key="category.id"
v-for="category in categories">{{ category.name }}</button>
</div>
<div class="col">
<p v-for="product in showProducts('all')"
:key="product.id">{{ product.name }}</p>
</div>
</div>
</div>
</template>
And the code for the Pinia store:
import { defineStore } from 'pinia'
import axiosClient from '@/axios'
export const useProductStore = defineStore( 'products', {
id : 'products',
state: () => {
return {
products: [],
categories: [],
}
},
actions: {
async getProducts()
{
axiosClient.get('products')
.then((response) => {
const data = response.data
this.products = data.products
this.categories = data.categories
})
}
},
getters: {
showProducts: (state) =>
{
return (categoryID) =>
{
if(categoryID === 'all')
{
return state.products
}
return state.products.filter((product) => product.productCategoryID == categoryID)
}
}
},
})
The initial data is loaded and show,but on click event is not showing filtered data (the showProducts method is fired and products are filtered, but the list is not visually changed).
What am I doing wrong here? What
const { showProducts } = productStorei guess its losing its reactivity. TryproductStore.showProducts