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

Yep, implementing conditional logic with the `when` keyword and radio buttons

I seem to be encountering an issue with my implementation (probably something trivial). I am utilizing React Hook Form along with Yup and attempting to establish a condition based on the selection of a radio group. The scenario is as follows: if the first ...

Using Jquery to load a css background image with a loader

I am seeking suggestions on how to display a loader between button clicks while waiting for a background image to fully load. Thank you <html > <head> <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script type= ...

Is there a way to dynamically modify the text of an HTML button element with jQuery?

My goal is to modify the text value of an HTML code using jQuery... <div class="dropdown"> <button type="button" class="btn btn-secondary dropdown-toggle button-text" data-toggle="dropdown><span>1395</span></button> ...

Dealing with the Back Button Problem in History API and History.js

Using Ajax to load the page presents a challenge when the user clicks the back button. Here is the scenario: Initial page (index.php) is loaded User clicks on a link The new page loads successfully via Ajax User clicks the back button The initial page is ...

Trouble deploying Firebase Cloud Functions

I am attempting to implement the following two functions: exports.increaseWaitinglistCounters = functions.database .ref('waitinglists/$iid/$uid') .onCreate(async () => { await admin .database() .ref(`waitinglistCounters/$ii ...

Issue with the close button on ngb-alert not functioning properly

As I develop my website, I have incorporated an ngb-alert component to display an alert message to users upon login. While the alert itself is functioning properly, I have encountered an issue with the close button being misaligned, and I am struggling to ...

Having trouble with implementing the Drag API Function alongside Javascript Arrow Functions?

I've searched extensively for a similar question but couldn't find one, so I hope this is not a duplicate. Recently, I created a factory function to assist me with drag and drop functionality in my current project. However, I noticed varied beha ...

Please provide the date using the Foundation Datepicker tool

Beginner in JavaScript here! I am having an issue with submitting dates selected using the Foundation Datepicker from . I have searched for solutions on StackOverflow like Post form on select with JQuery Datepick, but none seem to work in my case. If a Ja ...

Designing a slider to display a collection of images

I am currently working on a slider project using HTML, javascript, and CSS. I'm facing an issue where only the first two images (li) are being displayed and it's not transitioning to the other (li) elements. Below is the HTML code snippet: <se ...

Clicking on a jQuery element will reveal a list of corresponding elements

I've retrieved a list of elements from the database and displayed them in a table with a button: <a href="#" class="hiden"></a> To show and hide advanced information contained within: <div class="object></div> Here is my jQ ...

Issues with jQuery autocomplete functionality on certain elements are not uncommon

I've been experimenting with creating a user script for Opera using Greasemonkey to implement autocomplete functionality on input elements within web pages. However, I've encountered some issues with the script not working as expected. Initially ...

Deploying Nuxt with IIS: A Step-by-Step Guide

I am struggling to deploy Nuxt in IIS using IIS Node. The npm run start command works on my server, but since I have other projects like admin and API (.net) running on port 80, it is occupied. However, the structure works fine in IIS. Here is the code sn ...

What could be causing the HelloWorld program in AngularJS to malfunction?

To access the codes, you can visit http://jsfiddle.net/hh1mye5b/1/ Alternatively, you can refer to: <!doctype html> <html ng-app="dcApp"> <head> </head> <body> <div> <div ng-controller="SpeciesController"> ...

Storing data using angular-file-upload

In my application, I am utilizing the "angular-file-upload" library to save a file. Here is the code snippet that I am using: $scope.submitForm = function(valid, commit, file) { file.upload = Upload.upload({ url: '/tmp', data ...

After the Parent Component has successfully mounted, the Child Component will render

I am currently working with a third party library that has a unique prop allowing the user to pass in a string which is used to retrieve a DOM element and return its bottom value. <Sticky bottomBoundary="#some-id"> <MyChildComponentMightBeANa ...

What is causing the consistent occurrences of receiving false in Angular?

findUser(id:number):boolean{ var bool :boolean =false this.companyService.query().subscribe((result)=>{ for (let i = 0; i < result.json.length; i++) { try { if( id == result.json[i].user.id) ...

Error: The term "User" has not been previously defined

I encountered an issue while attempting to authenticate via vkontakte (vk.com) using passport-vkontakte. Error: A ReferenceError: User is not defined Below is the content of my auth.js file. var express = require('express'); var passport ...

Is there a way to duplicate an image a specified number of times depending on a given output value?

As a beginner in coding, I am looking to learn how to dynamically insert multiple images based on input and output values. Currently, my code for basic addition looks like this: <form oninput="x.value=parseInt(a.value)+parseInt(b.value)"> <inpu ...

Hovering over a Raphael animation - What's preventing it from functioning?

I'm currently working on a pie chart using Raphael, and I want to add a tooltip that displays text when hovering over a specific segment of the chart. The hover event is functioning correctly, but I'm having trouble adjusting the tooltip text coo ...

The reason why Express is not directing to the static React build files is due to the absence of a specific URL slug

The Scenario Currently, I'm in the process of developing a React application that is being served statically through Express. To clarify, the React app is constructed using npm run build and the resulting static files are stored within the build/ ...