I am struggling with the function of my reducer to add an item and increase its quantity if already present in cart. What my code does so far is adding another "quantity" with 1 instead of updating the quantity already present in my state.
Here's my code :
reducer :
import { ADD_TO_CART } from "../actions/types";
export default function(state = [], action) {
switch (action.type) {
case ADD_TO_CART:
if (state.findIndex(el => el.item.title === action.item.title) === -1) {
return [...state, { item: action.item, quantity: action.quantity + 1 }];
} else {
return [...state, { quantity: action.quantity + 1 }];
}
default:
return state;
}
}
action :
import { ADD_TO_CART } from "./types";
import axios from "axios";
export const addToCart = id => dispatch => {
axios
.get(`https://api.itbook.store/1.0/search/${id}`)
.then(items =>
items.map((item, quantity) =>
dispatch({
type: ADD_TO_CART,
item,
quantity
})
)
);
};
Thanks