I'm confused why my pinia is still displaying as undefined. Is there a way for my app to pause until pinia has finished loading before I filter the products by ID?

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.

Answer №1

Here's the solution that worked for me

Sharing it here in case someone else is facing the same issue as I did

Maybe this is a simple fix, but I'm putting it out there anyway

brandDetail.vue

<script setup>
import { useRoute } from 'vue-router'
import { ref, reactive } from "vue";
import axios from 'axios'
import { useProductsStore } from "../stores/products";
import Card from 'primevue/card';


const store = useProductsStore();
const baseURL = "http://127.0.0.1:8000/"
const route = useRoute()
const brandId = route.params.id


// fetching brand details
const brandDeets = ref({
    id: "loading",
    name: "Loading"
})
async function getBrandDeets(id) {
    const link = baseURL + "brands/" + id
    try {
        const data = await axios.get(link)
        brandDeets.value = data.data;
    } catch (error) {
        console.log(error);
    }
};
getBrandDeets(brandId)


// filtering products by brandID
let filteredProducts = reactive([]);
store.fetchProducts()
    .then(() => {
        const prods = store.products.filter(x => x.brand.id == brandId)
        filteredProducts.push(prods)
    })

</script>
<template>
    <div class="branddetails">
        <button @click="$router.go(-1)">Back</button>
        <div>
            <h1>Brand Details</h1>
            <hr>
            <h3>Brand Name: {{ brandDeets.name }}</h3>
            <p>ID: {{ brandId }}</p>
            <br>
        </div>
        <div>
            <h2>{{ brandDeets.name }} Products</h2>
            <hr>
            <div v-if="!filteredProducts[0].length == 0" class="productCardCont">

                <Card v-for="product in filteredProducts[0]" class="productCard">
                    <template #title>{{ product.name }}</template>
                    <template #content>
                        <p>SKU: <router-link :to="'/catalog/' + product.id">{{ product.sku }}</router-link></p>
                        <p>Description: {{ product.description }}</p>
                    </template>
                </Card>
            </div>
            <p v-else>No Products Found</p>
        </div>

    </div>
</template>

A big thank you to everyone who assisted me!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The sonar scanner encountered an error while attempting to parse a file using the espree parser in module mode

While executing sonar-scanner on a node project, I encounter a Failed to parse file issue, as shown below: ERROR: Failed to parse file [file:///home/node-app/somedir/index.js] at line 1: Unexpected token './AddCat' (with espree parser in mod ...

Issue with Bootstrap Scrollspy: Scrollspy function not functioning as expected

I need help with creating a one-page website where the navbar links change based on the section of the page you are on. I tried implementing it using HTML, but it didn't work out as expected. The code I used was within the container holding different ...

One way to generate div elements based on the number in an input field when a button is clicked, but ensuring it only happens once

What I am attempting to achieve is: Retrieve data from a JSON file upon button click. Display the data in separate boxes, each one different for every element of the array. For instance, if the JSON provides 3 rows of data, there should be 3 distinct box ...

Navigating the waters of adding a CSS property to a jQuery variable pseudo selector

Is there a way to adjust the top position for $myClass both before and after? I attempted to do so with the following code: var $myClass = $(".myclass"); $myClass.filter(":before,:after").css("top",-23); ...

Tips for creating a clickable A href link in the menu bar that triggers an accordion to open in the body when clicked - html

Is there a way to open the first accordion when clicking on the "open 1st accordion" link, and do the same for the second link? The accordions themselves work perfectly fine, I just need a way to trigger them from outside their scope by clicking on links i ...

Angular log out function to automatically close pop-up windows

Within my application, there is a page where users can open a popup window. When the user clicks on logout, it should close the popup window. To achieve this, I have used a static variable to store the popup window reference in the Global.ts class. public ...

The styles of a jQuery Mobile listview aren't updating properly when the list items are emptied and then dynamically re-created

When I have a listview that dynamically creates its list items using JavaScript code, everything works perfectly the first time the code runs. However, upon subsequent executions, the list is generated correctly but loses the jQuery Mobile styling. Despite ...

Managing data binding for checkboxes within a constantly changing set of options

I'm currently working on designing an angular directive for selecting items from a categorized list. Each item in the list should be selectable using a checkbox. The input data that will be provided to the directive looks something like this: [ { ...

Is it possible to generate a "pop-up" window upon clicking on the register button?

As a backend programmer, I'm looking to create a popup window that appears in front of the current window when users click "register", eliminating the need for redirection to another page. I believe you understand the concept. How can I achieve this? ...

I am looking to display data in Angular based on their corresponding ids

I am facing a scenario where I have two APIs with data containing similar ids but different values. The structure of the data is as follows: nights = { yearNo: 2014, monthNo: 7, countryId: 6162, countryNameGe: "რუსეთის ...

What is the procedure for utilizing Javascript to redirect a user on a website back to the login page if necessary?

Is there a way to redirect a website user back to the login page if they try to access a secure page without logging in first? I'm looking to implement this using JavaScript and cookies. Any suggestions or ideas on how to achieve this seamlessly for t ...

How can we pass props conditionally and ensure they are not undefined when using React useHistory for navigation?

In component1, I am redirecting the user to another page while passing props in the following way: onClick={() => history.push({ pathname: "/student/planandprice", state: { plan: history.plan.courseName, as: history.availableSession } })}& ...

Dropdown menu with multiple selection options

Is there a way to create a combobox that allows for multiple selections using either Javascript or HTML? While a typical combobox/dropdown structure does not support selecting multiple items, how can this functionality be achieved? ...

A proven method for distinguishing between desktop and mobile browsers

Similar Question: Exploring Browser Detection Methods in Javascript I am interested in finding an efficient way to differentiate between desktop and mobile browsers, either using JavaScript or PHP. if (desktop browser) { do x; } else { // mobi ...

Managing array elements in React: removing and duplicating items

One of my tasks is to incorporate a copy and delete button within a table. My goal is to pass the index from the map to the delete and copy onclick functions, however, I am encountering an issue where copying a row results in it having the same index as th ...

Does CausesValidation validate all validators, including validation groups?

I have encountered an issue with my web page where I have 3 separate validation groups, but when I attempt to submit the form, I want all of the groups to validate simultaneously. It appears that using causesValidation="true" on the button does not trigge ...

What is the reason for Firefox displaying the "excessive recursion" error message?

I have been working on generating an area Google chart using the code below, but I am running into an issue where Firefox is showing me a "too much recursion" error. The chart currently only has one point for testing purposes. Can anyone provide some gui ...

The console does not display the JSON data for requests and responses

I have successfully set up a server inside of VSCode, but unfortunately the request and response logs that I usually see in my terminal when running the server with npm start are not appearing. I would really like for them to display in the Debug Terminal ...

Oh no! Nuxt3 is throwing an error because it's unable to access the properties of undefined when trying to read 'options

When attempting to create a Nuxt 3 application, I encountered this error. At the moment, I have not yet utilized Axios and the project is mostly empty aside from the initial code. (base) app % npx nuxi build Nuxi 3.0.0 ...

Tips for sending information to a JavaScript variable through AJAX requests

Hello there, I'm currently working on a project that involves posting data stored in a JavaScript variable using AJAX. Can anyone assist me with the correct syntax for this process? <div class="container-fluid"> <div class="card shadow m ...