I have cloned this awesome shopping cart repo from https://github.com/vueschool/learn-vuex, it works good but doesn't handle data for my use case. For anyone who has used this repo, how do i extend it by getting products from database or Api?
Shop.js
const _products = [
{"id": 1, "title": "iPad 4 Mini", "price": 500.01, "inventory": 2},
{"id": 2, "title": "H&M T-Shirt White", "price": 10.99,
"inventory": 10},
{"id": 3, "title": "Charli XCX - Sucker CD", "price": 19.99,
"inventory": 5}
]
export default {
getProducts (cb) {
setTimeout(() => cb(_products), 100)
},
buyProducts (products, cb, errorCb) {
setTimeout(() => {
// simulate random checkout failure.
(Math.random() > 0.5 ||
navigator.userAgent.indexOf('PhantomJS') > -1)
? cb()
: errorCb()
}, 100)
}
}
Shop gets called via vuex actions
actions: {
fetchProducts({commit}) {
return new Promise((resolve, reject) => {
// make the call
// call setProducts mutation
shop.getProducts(products => {
commit('setProducts', products)
resolve()
})
})
}
You can use axios
to make a call to the server and get products like following
export default new Vuex.Store({
state: {
products: {},
},
actions: {
getProducts({commit},data) {
axios.get(`api/product?page=`+ data.page + '&orderBy='+ data.orderBy).then((response) => {
commit('updateProducts', response.data);
})
},
mutations: {
updateProducts (state, products) {
state.products = products
}
}
});