'Add product with Attributes to cart using redux
I need help in Reactjs app 'Add to cart'. I am using redux and to add products to cart with quantity and everything going right until tried to add specific attributes such as size or color and I don't know how to handle this can anyone explain me the logic to do it?
this is the reducer
case actionTypes.ADD_TO_CART:
const item = state.data.find((item) => item.id === action.payload.id);
const inCart = state.cart.find((item) =>
item.id === action.payload.id ? true : false
);
return {
...state,
cart: inCart
? state.cart.map((item) =>
item.id === action.payload.id
? {
...item,
qty: item.qty + 1,
selectedAttributes: [...item.selectedAttributes]
}
: item
)
: [...state.cart, {
...item, qty: 1,
selectedAttributes: []
}],
};
case actionTypes.ADJUST_ATTRIBUTES:
let selectedAttributes = [];
return {
...state,
cart: state.data.map((item) =>
item.id === action.id
? {
...item,
selectedAttributes: { [action.selectedAttributes.name]: action.selectedAttributes.value }
}
: item
),
};
this is action
export const addToCart = (itemID) => {
return {
type: actionTypes.ADD_TO_CART,
payload: {
id: itemID
}
}
}
export const selectAttribute = (itemID, name, value) => {
return {
type: actionTypes.ADJUST_ATTRIBUTES,
id: itemID,
selectedAttributes: {
name: name,
value: value
}
}
}
this is the radio button I want to select from it to add attribute
attribute.items.map((item, index2) => {
return (
<div className="button" key={index2}>
<input
onClick={() =>
this.props.selectAttribute(
this.props.currentItem.id,
attribute.name,
item.value
)
}
type="radio"
disabled={!this.props.currentItem.inStock}
name={`${this.props.currentItem.name}-${attribute.name}-${index}`}
value={item.value}
className="attributes-value"
/>
<label
className="attributes-label"
htmlFor={`${this.props.currentItem.name}-${attribute.name}-${index}`}
>
{item.value}
</label>
</div>
);
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
