Reputation: 120
I'm new to react native and i'm tryin to implement add to cart functionality using redux, It's working when pass the whole product to the cart, but that's not what i'm looking for because i have to add quantity and an input text with every product that user select, (to give the user ability to fill them before checkout). This is the main code (Working fine while passing the whole product)
const initialState = {
cart: [],
total: 0,
}
...
case ADD_TO_CART:
return {
...state,
cart: [action.payload, ...state.cart],
total: state.total + action.payload.price
}
...
This is what i'm trying now
const initialState = {
cart: [],
addCart: {
meal_id: '',
name: '',
price: '',
quantity: 1,
meal_details: ''
},
total: 0,
}
case ADD_TO_CART:
return {
...state,
addCart: {
meal_id: action.payload.id,
name: action.payload.name,
price: action.payload.price,
quantity: 1,
meal_details: ''
},
cart: [this.addCart, ...state.cart],
total: state.total + action.payload.price
}
But it gives errors,
this.addCart
add undefined to the cart array, I've tried addCart
return can't find variable addCart and i use state.addCart
it add first item as null arr and whenever i clicked on another product to add it adds the last one clicked
Upvotes: 0
Views: 185
Reputation: 3174
When accessing the Redux state, there's no this
. Also, you cannot access properties of an object as you're trying to changing the object, which is also the reason why your main code works but the second snippet does not. The simplest solution to fix your code will removing addCart
from your state, since the data is equivalent to your action.payload
, then creating the addCart object separately in the reducer.
const initialState = {
cart: [],
total: 0,
}
case ADD_TO_CART:
let addCart = {
meal_id: action.payload.id,
name: action.payload.name,
price: action.payload.price,
quantity: 1,
meal_details: ''
}
return {
...state,
cart: [addCart, ...state.cart],
total: state.total + action.payload.price
}
Upvotes: 1