Search code examples
javascriptvue.jsvuejs2vuex

how to use make a get request with vuex in vuejs


how can i store product in vuex this is 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 my axiosInstance file

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

this is 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 my template

<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>

i get the product json in my console

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

but i'm not seeing anything in my vuex store it returns this

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

please how can i store product in my vuex store and get it in my vue component


Solution

  • You are trying to commit with SET_PRODUCTS mutation

    commit('SET_PRODUCTS', products);
    

    But your mutation name is SAVE_PRODUCTS not SET_PRODUCTS

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