Simple Steps for Making a Get Request using Vuex in Vue.js

I'm trying to figure out how to store products in Vuex within my index component.

import Vue from 'vue'
import Vuex from 'vuex'
import cart from "./modules/cart";
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex)
export default new Vuex.Store({
  plugins: [createPersistedState()],
  modules: {
    cart,
  }
})

This is the axiosInstance file I am using:

import axios from "axios"
const API_URL = 'http://localhost:5000/api/';
let headers = {}
const axiosInstance = axios.create({
    baseURL:API_URL,
    headers,
})
export default axiosInstance

In my cart.js file:

import axiosInstance from "../../helpers/axiosInstance";
const state = {
  products: [],
};
const getters = {
  allProducts: state => state.products
};
const actions = {
  getProducts({
    commit
  }) {
    return axiosInstance
      .get('/products')
      .then(response => {
        console.log(response)
        let products = response.data;
        commit('SET_PRODUCTS', products);
        console.log(products);
        return products;
      })
      .catch(error => console.log('Failed to fetch products', error));
  }
};
const mutations = {
  SAVE_PRODUCTS(state, products) {
    state.products = products;
  }
};
export default {
  state,
  getters,
  actions,
  mutations
};

This is the template I have set up:

<template>
  <div>
      <li
        v-for="product in products"
        :key="product.id"
      >
       {{ product.price }}
      </li>
  </div>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
   computed: {
    ...mapGetters(['allProducts'])
  },
  mounted() {
    this.$store.dispatch('getProducts')
  }
};
</script>

When I view the product JSON in my console, it looks like this:

    {
        "_id": "6452bba224d63e39c56602c3",      
        "price": 200,
      
    },
    {
        "_id": "645396eed62c6accf63b186d",
        "price": 200,
        
    }
]

However, I am not seeing anything stored in my Vuex store. It currently returns:

state:products:[],
getters:allProducts:[],

Can anyone provide guidance on how to successfully store products in my Vuex store and retrieve them in my Vue component? Thank you!

Answer №1

Ensure that you are using the correct mutation name SAVE_PRODUCTS

commit('SAVE_PRODUCTS', products);

The mutation function should be named SAVE_PRODUCTS, not SET_PRODUCTS

SAVE_PRODUCTS(state, products) {
  state.products = products;
}

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

Can someone guide me on how to use contract.on() in ethers.js to listen to events from a smart contract in a node.js application?

I've been working on a node.js application using ethers.js to listen to events emitted from the USDT contract Transfer function. However, when I run the script, it exits quickly without displaying the event logs as expected. I'm unsure of what st ...

What is the best way to position a popup div in CSS?

Currently, I am in the process of developing a website that displays DVD details when hovering over an image, similar to what is shown in picture 1. However, I've encountered an issue where the content gets cut off for DVDs located on the right side o ...

Develop an application using ASP.NET MVC that allows for returning a JavascriptResult along with a

Imagine this situation When using MVC, it is quite simple to send a Javascript code back to the client for execution public ActionResult DoSomething() { return JavaScript("alert('Hello world!');"); } On the client side, ...

Performing a task after a process has finished

Currently, I'm working with node JavaScript and facing an issue where I need to run a new function after a loop has completed. In the code snippet provided below, // loop through objects in data, to process it represents a basic for loop iterating ove ...

Is there a way to temporarily toggle classes with jQuery?

Incorporating ZeroClipboard, I have implemented the following code to alter the text and class of my 'copy to clipboard button' by modifying the innerHTML. Upon clicking, this triggers a smooth class transition animation. client.on( "complete", ...

The toggle feature in Bootstrap is stuck in the "on" position and refuses to "untoggle."

Currently, I am working on developing a basic website using Laravel and Vue.js. To ensure that the website is responsive, I integrated Bootstrap 4 into the project. For the most part, everything appears to be functioning correctly - the navbar collapses as ...

Issue with querying and ordering products in Django using Python when passing values through the GET request

I have been working on a project where I need to filter products and sort them by price in ascending and descending order. Here is the code snippet from my view: def is_valid_queryparam(param): return param != '' and param is not None def f ...

The offsetTop property of Angular's nativeElement always returns a value of 0

I am currently working on a menu that will automatically select the current section upon scrolling. However, I am running into an issue where I am consistently getting a value of 0 for the offsetTop of the elements. The parentElement returns a value for of ...

What could be the reason for the esm loader not recognizing my import?

Running a small express server and encountering an issue in my bin/www.ts where I import my app.ts file like so: import app from '../app'; After building the project into JavaScript using: tsc --project ./ and running it with nodemon ./build/bin ...

Tips on resolving the flickering issue in dark mode background color on NextJS sites

One problem I am facing is that Next.js does not have access to the client-side localStorage, resulting in HTML being rendered with or without the "dark" class by default. This leads to a scenario where upon page reload, the <html> element momentari ...

The AutoComplete feature in Formik Field from Material UI component is not showing the InitialValues

Having an issue with displaying the initialValues in the AutoComplete component from the Material UI library when used in a Formik Field. Even though values are passed as initial, they do not render in the component, although if the form is submitted, they ...

javascript - the dropdown text remains static

Two dropdown fields are present: DropDownA and DropDownB, along with a checkbox. When the checkbox is checked, DropDownA will mirror the text, value, and selected index of DropDownB before becoming disabled. The issue at hand: Although the attributes ca ...

Struggling to set the value for a variable within an Angular factory?

When dealing with a variable as an array, I have no trouble pushing objects inside and retrieving the values within the controller. However, when trying to directly assign an object to that variable, I run into issues. If anyone can assist me in achieving ...

Lazy loading implemented with BootstrapVue's b-nav component

Having some trouble wrapping my head around the following issue: I've created a Vue.js component with tabs that have routes. I opted for a variation of the b-nav Tabs style (official docs) and it's functioning well in terms of tabs and routing. ...

Using Vue.js to pass an image URL as a prop for CSS animation by converting it to a CSS variable

Need help with a component that features a hover animation displaying 4 rotating images: animation: changeImg-1 2.5s linear infinite; @keyframes changeImg-1 { 0%, 100% { background-image: url('images/wel1.png'); } 25% { background-image: ur ...

Tips for populating a DOJO Select using JSON data that includes various parameters instead of just label and value

I am trying to populate a DOJO select element with JSON data where the item values for value are expressed by the code property. Here's an example of what I have: //require dojo Select var select = new Select({ name: "stateSelect", ...

What is the best way to utilize JavaScript variables that are declared on index.html/index.jsp in Vue.js?

Just starting out with Vue.js and I recently finished developing a Vue.js app using the terminal. I then deployed it on a Java web application and noticed that everything works fine when running it as is. However, I now need to pass a csrftoken to my Vu ...

The onClick function is called when I fail to click the button within a React form

I set up a form and I would like to have 2 ways to submit it: One by filling out the input field and pressing enter One by recording voice (using the react-speech-recognition library) However, after adding the second way, the input fi ...

After the form submission, my Next.js component keeps rendering repeatedly in a cumulative manner

I am currently working on a memory game application using Next.js, Node.js, and Express.js. I seem to be encountering an issue specifically with the login page. Initially, there are no issues when submitting the form for the first time. However, after the ...

Generate an array of identifiers from a pre-existing array

I am facing a challenge where I need to create an array of IDs for each element in an existing array whose size is unknown. The twist here is that every set of four elements should have the same ID. As an illustration, if the original array (let's ca ...