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

What is the best way to search for all results in MongoDB that have x appearing in any property?

Is it possible to search for all pictures in the mongoose framework with node and express that contain a specific parameter, regardless of which property holds that parameter? For example: If I enter "John Snow" in the search bar, I want to see all pictur ...

Blocking negative values when a button is clicked in Vue.js using v-on:click

How can I prevent the counter from going below 0 when clicked in this Vue component? Do I need to create a separate method to block it? Thank you for your assistance. <button v-on:click="counter.document -= 1">-</button> <h3>{{coun ...

Boost the frequency of updates in Meteor.observe

When Python writes to a database (mongo) every second in the setup, Meteor.js is expected to react immediately to the new record insertion. Issue: However, the use of cursor.observe() results in the console outputting only 4-5 seconds after the new record ...

Emulating user interaction using Prototype library - Simulate.js

I have set up a Prototype code to act as an observer, but I am facing issues triggering the observer after manually setting the value of the select element... select.observe('change', this.onChange.bindAsEventListener(this)); Initially, I tried ...

transfer a product attribute value to a different product attribute within the Magento platform

There is an attribute called Weight : Attribute Code: weight Scope: general Catalog Input Type for Store Owner: Text Field Values Required: yes Apply To: Simple Product, Bundle Product Allow HTML Tags on Frontend: yes Also, there is a General Weight attr ...

Problem with redirecting when using HTTPS

I recently implemented an SSL Certificate and made changes to the web.config file. Here is the updated code: <system.webServer> <rewrite> <rules> <rule name="removed by me" stopProcessing="true"> ...

Create a CSS menu that centers the links

Here is the CSS code I am using for my horizontal menu: nav { height: 40px; width: 100%; background: #F00; font-size: 11pt; font-family: Arial; font-weight: bold; position: relative; border-bottom: 2px solid # ...

Struggling to display the array after adding a new item with the push method

Seeking assistance in JavaScript as a newcomer. I have written some code to print an array once a new item is added, but unfortunately, it's not displaying the array. I am puzzled as there are no errors showing up in the console either. In my code, I ...

Exploring Next.js' dynamic routes with an alternative URL approach

Currently in the process of transitioning a React project to Next.js, I've encountered a minor issue with Dynamic Routing that doesn't seem to have any readily available solutions online. I have multiple information pages that utilize the same c ...

Are there any NPM packages available for extracting PDF metadata?

Does anyone know of an npm module that allows me to modify the metatags such as Author and Title in PDF files? I am also open to suggestions for any open-license JavaScript library that can do this job. I came across a program called pdftk, which seems s ...

When attempting to send emails, SendGrid encounters an error and fails to provide an error code

Earlier today, I successfully sent out a series of emails using SendGrid. It was quite a large number of emails, as I needed to create multiple user accounts with attached email addresses. Thankfully, everything went smoothly and all the emails were delive ...

How can I stop full-page auto-scroll screenshot extensions from automatically scrolling?

As the owner of a membership website, I'm faced with the challenge of preventing users from easily taking full page screenshots of the valuable text content in my members area. Many browser extensions, such as Fireshot and GoFullPage, enable auto-scro ...

What is the best method to update the accessor value of my react table depending on certain data conditions?

const data = { name:"test1", fclPrice:100, lclPrice:null, total:"50" } and here are the two columns: const Datatable = [ { Header: 'Name', accessor: 'name' }, { Header: 'Price', ac ...

Creating custom validation in Vuetify for password confirmation is essential in ensuring that

While developing a Vue.js template, I encountered a scenario on the sign-up page where I needed to compare passwords during user registration. To achieve this, I implemented a custom validation rule in the code snippet below: <v-text-field label=" ...

tag directive not functioning properly

I have encountered an issue while trying to create a simple custom directive. When I specify the directive as <div my-info></div> in my HTML file, it works fine. However, when I specify it as <my-info></my-info>, it does not work. ...

Utilizing React Typescript Discriminating Unions to choose between two different types based solely on props

In my project, I have a component that consists of different types: type Base = { color: string } type Button = { to: string } & Base type Link = { link: string linkNewTab: boolean } & Base type ComponentProps = Button | Link e ...

Having difficulty sending ajax to the controller function

Currently, I am facing an issue with updating my database using AJAX in Laravel. The goal is to change the value in the enable column from 1 to 0 when a toggle button is clicked. Below script is included in the view: $(".toggle-btn").change(function() { ...

JavaScript guide: Deleting query string arrays from a URL

Currently facing an issue when trying to remove query string arrays from the URL. The URL in question looks like this - In Chrome, it appears as follows - Var url = "http://mywebsite.com/innovation?agenda%5B%5D=4995&agenda%5B%5D=4993#ideaResult"; ...

JavaScript code that triggers a page refresh when an input is added to a form without actually inputting

Upon delving into extensive research on this particular subject, I regrettably came up empty-handed. My sincere apologies if this question has been posed before. The task at hand involves creating a form that prompts users to input information about four ...

Sort choices based on the optgroup category label text

I want to create a system where the user can select a game from one dropdown menu and then see only the consoles that game is available on in another dropdown menu. For example, if the user selects a game like Forza Horizon which is available on multiple c ...