I tried using useSelector Hook to access the state but it does not update the component until I leave and return back to the component
This is my functional Component, the function AddToCartAction is dispatchable
export default function DishDescription() {
const {menuCart} = useSelector(state => state.cartState);
const {user, sessionId} = useSelector(state => state.authState);
const dispatch = useDispatch();
function removeFromCart() {
RemoveFromCartAction(dish.id, user.id, sessionId)(dispatch);
}
function addToCart() {
AddToCartAction({
customerId: user.id,
restaurantId: dish.id,
menuId: dish.id,
quantity: 1,
price: dish.price,
temporalId: sessionId,
})(dispatch);
}
return (
//Some code here
);
}
This is the AddToCartAction function that adds to cart
export const AddToCartAction = ({customerId, restaurantId, menuId, quantity, price, temporalId}) => {
const menuOrder = {
customerId,
restaurantId,
menuId,
quantity,
price,
temporalId,
};
return dispatch => {
dispatch({
type: ADD_TO_CART,
payload: menuOrder,
});
};
Here is the Reducer
export const cartReducer = (state = initialState, action) => {
if (action.type === ADD_TO_CART) {
const updatedCart = state.menuCart.map(cart => (cart.menuId === action.payload.menuId ? {...cart, quantity: cart.quantity + 1} : cart));
return {
...state,
menuCart: updatedCart,
};
}
return state;
};