Here is my issue with a Vue single file component that should display products sold by a specific brand ID. Despite fetching the products and filtering them based on the brand.id, the products array remains undefined.
<script setup>
import { useRoute } from 'vue-router'
import { ref, computed } from "vue";
import axios from 'axios'
import { useProductsStore } from "../stores/products";
const store = useProductsStore();
const baseURL = "http://127.0.0.1:8000/"
const route = useRoute()
const id = route.params.id
store.fetchProducts()
const getProductsById = store.getProductsByBrandId
</script>
<template>
<div class="brandDetails">
<div>
<h2>Brand Details</h2>
ID: {{ id }}
</div>
<div>
<h2>Products</h2>
<p v-for="product in getProductsById(id)">{{ product.name }}</p>
</div>
</div>
</template>
Additionally, I have included my pinia store.js below:
import { defineStore } from "pinia";
import axios from "axios";
export const useProductsStore = defineStore("products", {
state: () => {
return {
products: [],
vendors: [],
brands: [],
};
},
getters: {
getProducts: (state) => {
return state.products;
},
getVendors: (state) => {
return state.vendors;
},
getBrands: (state) => {
return state.brands;
},
getProductsByBrandId: (state) => {
return (id) => state.products.filter((x) => x.brand.id === id);
},
},
actions: {
async fetchProducts() {
try {
const data = await axios.get("http://127.0.0.1:8000/products.json");
this.products = data.data;
} catch (error) {
alert(error);
console.log(error);
}
},
async fetchVendors() {
try {
const data = await axios.get("http://127.0.0.1:8000/vendors.json");
this.vendors = data.data;
} catch (error) {
alert(error);
console.log(error);
}
},
async fetchBrands() {
try {
const data = await axios.get("http://127.0.0.1:8000/brands.json");
this.brands = data.data;
} catch (error) {
alert(error);
console.log(error);
}
},
},
});
I suspect the issue lies in attempting to filter an undefined array. If so, how can I ensure it's defined before filtering? Perhaps there is a better approach that I am overlooking. Any assistance would be greatly appreciated.