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);
},
},
});