Hi there,
I am new to web development and I am currently trying to build an e-commerce website as a project.
I managed to build the front-end using Vue and Vuex to store the shopping cart. I would now like to be able to save the Shopping Cart Items into my database if the user is logged in.
I created a model for it: ShoppingCartItem
-Quantity
-Price
-User: One-to-One user_permissions_user
-Variation: One-to-One variation (each product has different variations which have a product reference)
I set the permissions so that authentificated users can post/find/get etc
Right now in Vuex my addToCart action looks like this:
addToCart({ commit }, cartItem) {
var found = false;
var index;
for(var i = 0; i < this.state.cart.length; i++) {
if (this.state.cart[i].variation.Reference == cartItem.variation.Reference) {
found = true;
index = i;
break;
}
}
if (found) {
if (user) {
axios.put('http://localhost:1337/shopping-cart-item', { variation: { Reference: cartItem.variation.Reference }, users_permissions_user : { id: user.user.id }}, { quantity: this.state.cart[index].quantity + 1 }, { headers: authHeader() })
}
this.state.cart[index].quantity+=1
} else {
if (user) {
axios.post('http://localhost:1337/shopping-cart-item', { ...cartItem, user: user.user }, { headers: authHeader() })
.then(() => commit('addToCart', { ...cartItem, user: user.user }))
} else {
commit('addToCart', { ...cartItem, user: 'guest' })
}
}
I changed the update service to look like this:
async update(params, data) {
const existingEntry = await strapi.query('shopping-cart-item').findOne(params);
const isDraft = isDraft(existingEntry, strapi.models.shopping-cart-item);
const validData = await strapi.entityValidator.validateEntityUpdate(
strapi.models.shopping-cart-item,
data,
{ isDraft }
);
const entry = await strapi.query('shopping-cart-item').update(params, validData);
return entry;
}
But I am unsure if params is a customizable object or if it’s a req.params equivalent. I do not have the object id so I removed :id from the route.
I am pretty sure the update feature must have many problems, but as a start I am wondering why the post method doesn’t work.
axios.post('http://localhost:1337/shopping-cart-item', { ...cartItem, user: user.user }, { headers: authHeader() })
The cartItem is built on the frontend and only missing the user info, which I get in Vuex
const user = JSON.parse(localStorage.getItem('user'));
I know a lot of this code needs to be refactored / put into functions but right now I just want to understand how it works before I abstract many things out of it.
At this point I would be okay to pay for mentorship to be able to understand all this a bit better.
Thanks for your help!