When the page is reloaded, the computed property in Vue.js (vuex) returns undefined due to the hardcoded array of objects data stored in vuex

I am facing an issue in my Vue shoe shop project where I am encountering 'undefined' error upon page reload while trying to access a getter through a computed property in the ShoeDetail component. My Vuex state contains hardcoded array of objects data. In the Shoe component, I iterate through this data using v-for and display all available shoes in the Men view successfully. Each shoe image has a click event that loads a new route with detailed information for that specific shoe based on the clicked id. I have a getter in Vuex:

getProductById: (state) => (id) => {
      return state.sneakers.find((sneaker) => sneaker.productId === id);
    },

which I access through a computed property:

   product() {
      return this.$store.getters.getProductById(this.$route.params.id);
    },

This setup allows me to display the data stored in the Vuex state using interpolation like:

{{product.brand}}

However, upon page reload, I encounter the following error:

**[Vue warn]: Error in render: "TypeError: Cannot read property 'brand' of undefined"
found in
---> <Detail> at src/components/ShoeDetail.vue
       <App> at src/App.vue
         <Root>**

I have tried using v-if="product", but since there is no API call involved, this does not seem to be the issue. I have also attempted to use createPersistedState, but the problem persists. Any insights on why I am getting 'undefined' upon page reload would be greatly appreciated.

Here is my Vuex setup:

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    import Vue from 'vue';
    import Vuex from 'vuex';
    import createPersistedState from 'vuex-persistedstate';

    Vue.use(Vuex);

    export default new Vuex.Store({
      plugins: [
        createPersistedState({
          key: 'keyname',
          storage: window.localStorage,
        }),
      ],
      state: {
        // Array of sneakers data
        sneakers: [
          {
            productId: 1,
            productno: 1234,
            brand: 'nike',
            gender: 'men',
            size: 5,
            price: 150,
            image: require('@/assets/images/nike-air-zoom.jpg'),
          },
          // More sneaker objects
        ],
      getters: {
        // Getter to retrieve all products
        getProducts: (state) => {
          return state.sneakers;
        },
        // Getter to retrieve a product by ID
        getProductById: (state) => (id) => {
          return state.sneakers.find((sneaker) => sneaker.productId === id);
        },
      },
    });

Answer №1

Appreciate the solution! I managed to resolve the issue by incorporating parseInt into the computed property of ShoeDetail.

  computed: {
    item() {
      return this.$store.getters.getItemById(
        parseInt(this.$route.params.id)
      );
    },
  }

Answer №2

Make sure to follow these steps in the ShoeDetail component:

data: () => {
    data: '',
},
methods: {
    getProduct () {
    this.product = this.$store.getters.getProductById(this.$route.params.id);
    },
},
mounted () {
    this.getProduct();
}

By doing this, the functionality should be up and running smoothly :)

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

Passing the contents of a datatable as parameters to a PHP script

I am facing a challenge with my datatable that has two columns, "Name" and "Age". After populating the datatable using Ajax, I create a button for each row. The goal is to send the "Name" and "Age" fields of the clicked row to a PHP script, which will then ...

Issues persist with AngularJS integration using Modernizr

Incorporating AngularJS and Modernizr, I aim to identify media queries and trigger a function whenever the window or viewport is resized. My goal is to control element visibility based on whether the user is on a desktop or mobile device - certain elements ...

Error detected (unresolved promise): Invalid JSON format is causing an Unexpected token < at the beginning of data position (Application built with React/Redux)

I'm in the process of setting up user authentication using JWT. I've successfully created an API for this purpose. Now, my goal is to integrate this authentication API with my React/Redux App. When a user signs up, I trigger an action from my S ...

Breaking down object properties to 'this' using destructuring in javascript

I would like to set the pagination result from response.data to Vue data. The standard approach would be: this.resultData = response.data.results this.totalResults = response.data.total this.perPageResults = response.data.per_page However, ...

Having trouble displaying specific images on React Native, how can I resolve this issue?

I am currently developing a weather application that retrieves weather information and displays it using ForecastItem components. However, I have noticed that some of the components do not display the weather image randomly. On the Home screen, I use the ...

What is the best way to ensure that the table header is printed on every page when printing?

My table has a large number of dynamic rows, and when I try to print or preview it using the window.print() function, only the table header (thead) appears on the first page. How can I make sure that the table header appears on each printed page? <div ...

The CubeCamera function is encountering an issue where it is unable to access the 'up' property due to it being undefined

After a long time, I revisited my three.js project and was reminded of the days when I used to type out the full name PlaneBufferGeometry. The project features several vehicles that are supposed to reflect their environment (and each other) through the use ...

Navigating through history using the pushState method and incorporating back and forward buttons

I am trying to implement back and forward buttons functionality with this ajax method The code is working well, and the URL in the browser is changing as expected However, when I click on the back and forward buttons, nothing happens (function(){ ...

Replacing jQuery.ajax from a different directory/domain - problem with using relative URLs

We are incorporating scripts from various sources and domains, including one that contains the definition for jQuery.ajax function. Calls to jQuery.ajax are being made from different places and domains using relative URLs, such as jQuery.ajax("my/relativ ...

Having trouble compiling jsx with gulp, webpack, and the babel-loader combination

UPDATE: vue-tables-2 has been updated to now come pre-compiled, eliminating the need for loaders. When using the templates option, it is recommended to utilize scoped slots, which do not require any special configurations. I am currently utilizing gulp, w ...

Can you explain the distinction between the "DOMContent event" and the "load event"?

Within Chrome's Developer tool, there is a blue vertical line marked "DOMContent event fired", as well as a red line labeled "load event fired". Is it safe to assume that the "DOMContent event fired" signifies the initiation of inline JavaScript execu ...

Incorporate query strings into every hyperlink within the application

Let me paint you a picture... I've got this lovely Next.js app that's been around for a while, filled with lines of code we've poured our hearts into. Recently, we decided to spice things up by running some ads and now we are itching to see ...

How can I add .htaccess to Vue production when using npm run build?

While using Vue CLI 3 and vue-router with history mode, I encountered this particular issue. Upon further investigation, I discovered that inserting a .htaccess file inside the dist folder after running npm run build resolved the issue. Is there a way to ...

Having trouble with a 400 bad request error, could the method be incorrect?

Hey there, I'm currently facing a bit of a roadblock and not exactly sure what's causing the issue. My Postman login seems to be working fine, but my backend isn't accepting anything, so I suspect there might be something wrong with my meth ...

Having trouble sending data from AJAX to PHP

My goal is to implement a "load more" feature in my web app that automatically calls a PHP file to load additional products as soon as the page is fully loaded. In order to achieve this, I am using AJAX to call the PHP file: $(document).ready(function() { ...

Mapping an array with array objects - a guide to connecting and iterating through

I am working with two arrays: ['x', 'y', 'z'] And array 2: [{ x: 5, y: 10, z: 15, w: 20 }] Is there a way to merge these two arrays to get the following output: [{x: 5, y: 10: z: 15}] I only want the items present in the fi ...

Utilize the HTML webpack plugin to include the rendered file within the router

Hey there! I'm currently dealing with a frustrating issue. I can't seem to locate the index.html file generated by html-webpack-plugin for rendering. Even though I can access it at localhost:8080/index.html, I'm struggling to figure out how ...

issue with leaflet vue3 component showing incorrect marker popup when clicked

I am dynamically loading markers based on the bounding box from an API using a Pinia store. These markers are stored in the itemsList property of my map wrapper component map-view. The markers are rendered as circlemarkers inside a Vue-for loop. As I navi ...

Issue with hook not updating when invoked inside useEffect

I'm encountering an issue with updating the state after fetching data from my API. The API response seems to be correct, but for some reason, my weatherData-hook is not getting updated and it returns undefined. Can anyone point out what mistake I migh ...

Is it possible to update the value of Select2 as you type?

In my country, the majority of people do not have a Cyrillic keyboard on their devices. To address this issue, I created a function that converts Latin characters to Cyrillic in Select2's dropdown for easier city selection. However, I noticed that the ...