Garmaine Staff asked 4 months ago

I am working on a reactjs app which uses redux for state management. But I got into some issue here. In the productDetailpage.js I have a add To Cart button when user clicks on it add product to the cart and the add to cart changes to add to cart. But the problem comes when user goes to any other product it already shows added to cart. We need to refresh to make it add to cart again.

Here is my code

ProductDetail/BottomDrawer.js

 <Grid item xs={6}>
                    <Button
                      disableRipple={true}
                      className="btn"
                      variant="outlined"
                      onClick={addToCart}
                    >
                      {addedToCart ? "Added To Cart" : "Add To Cart"}
                    </Button>
                  </Grid>

addToCartActions.js

export function addToCart(product, quantity) {
  return dispatch => {
    dispatch({
      type: "ADD_TO_CART_LOAD"
    });
    new _rest()
      .post(URLConstants.urls.ADD_TO_CART, {
        optionVariationId: null,
        productId: product.productId,
        quantity: quantity
      })
      .then(response => {
        dispatch({
          type: "ADD_TO_CART_SUCCESS",
          payload: response.data
        });
      })
      .catch(error => {
        return dispatch({
          type: "ADD_TO_CART_ERROR",
          payload: error
        });
      });
  };
}

addToCartReducer.js

const initialState = {
  loading: false,
  loaded: false,
  error: null,
  itemsInCart: null,
  pagination: null,
  totalamount: 0,
  checkedItems: [],
  paymentStatus: "NIL_TRANSACTION",
  order: {
    addressId: "NIL",
    paymentType: "NIL"
  },
  bulkOrderData: []
};

export default function (state = initialState, action) {
  switch (action.type) {
    case "ADD_TO_CART_LOAD":
      return {
        ...state,
        loading: true
      };

    case "ADD_TO_CART_SUCCESS":
      return {
        ...state,
        loading: false,
        loaded: true,
        addedToCart: action.payload
      };

    case "ADD_TO_CART_ERROR":
      return {
        ...state,
        loading: false,
        error: action.error
      };