2

I am trying to building a shopping cart utilizing the context API and the useReducer Hook, I have this functionality where the user need to click to a button to add an item to the shopping cart and the app will make an api request to add the item on the server and it will return the item to the front-end and the app will dispatch an action to update the UI and the same for removing item from the cart, but the thing is that the app is not updating the UI till I refresh the page.

  const handleAddingToCart = async () => {
    setLoading(true);
    const response = await addToCart({ itemId: id, quantity: 1 }, token);
    setLoading(false);

    cartDispatch({
      type: "ADD_ITEM",
      payload: response.data.data,
    });
  };

cart reducer:

case "ADD_ITEM": {
      return {
        ...state,
        items: [...state.items, action.payload],
      };
    }

    case "REMOVE_ITEM": {
      return {
        ...state,
        items: state.items.filter((item) => item !== action.payload),
      };
    }

this is my function to handle this, hope you guys can help, thank you so much in advance.

AN Dev
  • 31
  • 1
  • 1
  • can you show your response data structure? – EugenSunic Aug 17 '20 at 22:03
  • 1
    the response is the new item that was added to the cart. – AN Dev Aug 17 '20 at 22:29
  • Hey Eugen, thank you so much for your comment. I just want to let you know that I managed to fix the problem like this but I am not sure if I following the best practice, here is what I did, I change the reducer case for remove item to be like this: case "REMOVE_ITEM": { const itemIndex = state.items.findIndex(ie => ie.itemId === action.payload) return { ...state, items: [ ...state.items.slice(0, itemIndex), ...state.items.slice(itemIndex + 1), ], }; } – AN Dev Aug 17 '20 at 23:22
  • defiantly will do, this is my first question so it looks bad, sorry for this sir. – AN Dev Aug 17 '20 at 23:25

0 Answers0