0

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

Charlote22
  • 1,035
  • 3
  • 11
  • 13

2 Answers2

1

You are finding the index (which is great) but not doing anything with it (which is not so great):

import { ADD_TO_CART } from "../actions/types";

export default function(state = [], action) {
  switch (action.type) {
    case ADD_TO_CART:
      const index = state.findIndex(el => el.item.title === action.item.title);
      if (index === -1) {
       return [...state, { item: action.item, quantity: action.quantity + 1 }];
      } else {
        // Use map to create a new state object 
        return state.map((item, i) => 
            index === i //Only modify the found index
            ? { ...item, quantity: item.quantity + action.quantity }  //Add the required quantity to the current quantity (not too sure about this)
            : item //Don't modify other items
        );
      }
     default:
       return state;
  }
}
apokryfos
  • 38,771
  • 9
  • 70
  • 114
  • Thanks it works (well I had to add another "+1" after "action.quantity inside the ternary so it adds 1 each time). Thanks for the explanation. I didn't think about reusing the index. – Charlote22 Dec 28 '18 at 09:33
0
import { ADD_TO_CART } from "../actions/types";

export default function (state = [], action) {
  switch (action.type) {
    case ADD_TO_CART:
      const index = state.findIndex(el => el.item.title === action.item.title);
      if (index > -1) {
        const newState = [...state];
        newState[index] = { ...newState[index], quantity: action.quantity + 1 };
        return newState;
      } else {
        return [...state, { ...action.item, quantity: action.quantity + 1 }];
      }
    default:
      return state;
  }
}
Alfred Ayi-bonte
  • 715
  • 7
  • 11