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!