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.