The Vue warning states that the property "$store" was attempted to be accessed during rendering, but it is not defined on the current instance

Hello, I am new to the world of web development and currently working on an online shop project. I have encountered two errors that I'm struggling to fix:

1) [Vue warn]: Property "$store" was accessed during render but is not defined on instance.

2) Uncaught TypeError: Cannot read properties of undefined (reading 'state')

This is what my Store.js file looks like:

import { createStore } from 'vuex'
import axios from "axios";

const store = createStore({
    state:{
        products:[]
    },
    mutations:{
        SET_PRODUCTS_TO_STATE:(state,products)=>{
            state.products = products;
        }
    },
    actions:{
        GET_PRODUCTS_FROM_API({commit}) {
            return axios('http://localhost:3000/products',{
                method:"GET"
            })
                .then((products) =>{
                commit('SET_PRODUCTS_TO_STATE',products.data);
                return products;
            })
                .catch((error)=>{
                    console.log(error)
                    return error;
                })
        }
    },
    getters:{
        PRODUCTS(state){
            return state.products;
        }
    }

});
export default store;

And here is a snippet from my v-catalogue.vue file:

<template>
  <div class='v-catalog'>
  <h1>Catalog</h1>
<div class="v-catalog__list">
  <v-catalog-item
  v-for="product in this.$store.state.products"
  :key="product.article"
  v-bind:product_data="product"
  @sendArticle="showChildArticleInConsole"
  />
</div>
  </div>
</template>

You can find the full repository for this project here: https://github.com/BIGBASEDFLOPPA/Project1

Answer №1

By removing the word "this," everything will function correctly.

v-for="item in $store.state.items"

Remember to include "this" in the script section, but avoid using it in the template part.

Answer №2

If you are using Vue3.x, make sure to import the store in your someItem.vue file. Here is an example code snippet:

import { useStore } from 'vuex';
export default {
  setup(){
    let store = useStore()
    let products = store.state.products

    return {
      products
    }
  }
}

// Now you can use the products in your template by looping through them
v-for="product in products"

Answer №3

Utilizing the mapState helper can help you maintain cleaner code.

To begin, make sure to import it:

import { mapState } from "vuex";

Include it within the computed section using the spread operator for a simpler syntax:

computed: {
   ...mapState(['items']),
},

You can now access products directly without referencing $store.state:

<v-item v-for="product in products" ...

Answer №4

If you're working with Vue 3, there's no need to create a store.js file. Instead, simply include the following code snippet within your v-catalog.vue file:

 <template>
  <div class='v-catalog'>
    <h1>Catalog</h1>
    <div class="v-catalog__list">
      <v-catalog-item
        v-for="product in products"
        :key="product.article"
        v-bind:product_data="product"
        @sendArticle="showChildArticleInConsole"
      />
    </div>
  </div>
</template>
<script>
import vCatalogItem from './v-catalog-item';
import axios from "axios";

export default {
  components: {
    vCatalogItem
  },
  name: "v-catalog",
  data() {
    return {
      products: []
    }
  },
  async created() {
    try {
      const res = await axios.get('http://localhost:3000/products');
      this.products = res.data;
    } catch (e) {
      console.error(e);
    }
  }
}
</script>

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

"Troubleshooting Error: When accessing a property in AngularJS,

My goal is to retrieve a date value. However, I encounter an error message saying 'Cannot read property 'NTLI' of undefined' whenever the checkbox is unchecked and the date picker is invisible. Strangely enough, everything works fine wh ...

Utilizing JSON format for submitting dynamic form data

When using AJAX post, I have successfully passed predefined data like this: //var data = {"name": "Testing", "email": "[email protected]", "cpf": "9876543210"}; However, I am facing difficulty in dynamically passing the form data. I would appreciat ...

The Exported Module 'Auth' is Not Available in AWS Amplify Auth Requested

Currently working on developing an AWS Amplify application using VueJS. amplify add auth amplify push amplify env pull dev I have successfully integrated an Auth module, where authentication is functioning based on this example utilizing the authenticator ...

Adjust the href link value when a new option is selected

I currently have a select element displayed below. Next to it, there is a link that sets the eID value to a session value. However, I want this value to be updated dynamically whenever a different eID value is selected from the dropdown. Although I can r ...

Exciting jQuery animations and transitions

Is there a way in JavaScript to call function or method names using a string? For example, when writing jQuery code that applies an effect to specific targets, can the effect be dynamic and changeable by the user? I'm hoping for something like jQuer ...

Implementing a function to specify size limits

As a newcomer to the world of JavaScript, I am facing a particular challenge. My goal is to add a conditional statement in my code that will only execute on screen sizes larger than 768px. $(window).on('scroll', function () { if ($(window ...

A more efficient method for changing all corresponding properties located at varying depths within a nested object

When working with JSON data from an API, I often need to parse and modify specific property values. The challenge arises when the nesting structure of the JSON data is inconsistent and beyond my control. For example, I cannot always rely on a fixed depth ...

The intricacies of converting AudioBuffers to ArrayBuffers

I currently have an AudioBuffer stored on the client-side that I would like to send through AJAX to an express server. This link provides information on how a XMLHttpRequest can handle sending and receiving binary data in the form of an ArrayBuffer. In m ...

Utilize Vue to call a method by providing its name as a string

When designing a navbar, I encountered the need to include a list of buttons. Some of these buttons should act as links, while others should call specific methods. For example, clicking on "Home" should direct the user to /home and clicking on "Log out" sh ...

Mastering Anchors in AngularStrap ScrollSpy

Is there a way to effectively utilize AngularStrap's ScrollSpy feature to link to anchors within the same document? Upon reviewing the AngularStrap documentation, I noticed that when a link is clicked, a double hash is generated in the URL. For examp ...

Can you explain how to break down secured routes, users, and posts all within a single .create() function in Mongoose/JavaScript

I am seeking guidance on utilizing the .create() method within a protected route while implementing deconstructed JavaScript. In the absence of the protected route, I can deconstruct my schema and utilize req.body in .create(...) as shown below. const { ti ...

The combination of space has been deactivated for concatenation

I have an array of skills that includes skills: [ "HTML5", "CSS3", "SCSS", "Bootstrap", "JavaScript", "Vue.js", "PHP", "MySQL", "Symfony" ] In my template, I'm trying to d ...

Using Ajax.BeginForm with BeforeSend functionality

My MVC website has multiple Ajax.BeginForm elements, and I am looking to handle the beforeSend event of my Ajax calls. While the code below works for manual jquery ajax calls, it does not seem to work with the Ajax.BeginForm helpers: $.ajaxSetup({ &a ...

Activate the timepicker in Bootstrap when the user clicks on the input field

Struggling to implement a timepicker feature? Look no further than this resource. After adding the necessary js and css to your project, you may encounter issues with the popup not appearing when clicked. The code provided offers a TextBox control with s ...

Solutions for resolving the error "Unable to access property 'value1' because it is undefined"

constructor() { super(); this.state = { value1 : Math.floor(Math.random() * 100), value2 : Math.floor(Math.random() * 100), value3 : Math.floor(Math.random() * 100), proposedAnswer : Math.floor(Math.random() * 3) + this.state.value1 + t ...

Understanding the functionality of app.listen() and app.get() in the context of Express and Hapi

What is the best way to use only native modules in Node.js to recreate functionalities similar to app.listen() and app.get() using http module with a constructor? var app = function(opts) { this.token= opts.token } app.prototype.get = function(call ...

Improve the efficiency of the function for retrieving data from a lengthy string and organizing it into key-value pairs within an object

I am dealing with a string extracted from a text file, which is structured in the following way on each line. 1=abc|2=TsMarketDataCache|3=1|4=141061|6=2023-02-27T05:04:50.472|36=F|7=1584A Format: key1=value1|key2=value2|key3=value3|key4=value4...|keyN=va ...

Is there a way to transmit React code using Express?

Currently, I'm in the process of creating a coloring demonstration. Initially, I had an SVG file at hand, but I made the decision to utilize svgr for its conversion into a React component. This strategy will offer me the flexibility to easily modify i ...

Can the background color of HTML header text be altered using JavaScript in JQGRID?

Can the background color of HTML header text be modified using JavaScript? Updated: Oops, I forgot to mention that it is for the header text in jqGrid. My apologies for that oversight. ...

Manipulate the content of any webpage without using external extensions by injecting your own HTML, CSS, and JavaScript code

I am currently following a tutorial on how to draw shapes on a local webpage using Canvas. I came across this helpful article on Html5 canvas paint. Everything is going smoothly, but now I am interested in replicating the drawing functions/CSS/HTML and "i ...