score:2

Accepted answer
case appConstants.UPLOAD_PRODUCT_SUCCESS:
  // (1) iterate the product images array
  return action.payload.reduce(
    (
      state,
      {
        productCode,
        productName,
        productCategory,
        imageFile,
        imageFileName
      }
    ) => {
      // (2) Check if the product is already in state
      const shouldUpdate = state.products.some(
        (product) => product.productCode === productCode
      );

      // (3a) If we just need to return updated state with added new image
      if (shouldUpdate) {
        return {
          ...state,
          // (4) shallow copy the products array
          products: state.products.map((product) =>
            product.productCode === productCode
              // (4b) If this is the matching product, shallow copy product
              // append a new image file object with new id
              ? {
                  ...product,
                  productImages: product.productImages.concat({
                    id: uuidV4(),
                    imageFile,
                    imageFileName
                  })
                }
              // (4b) copy forward existing product object
              : product
          )
        };
      }

      // (3b) Create a new product object and initially populate images array
      return {
        ...state,
        products: state.products.concat({
          productCode,
          productName,
          productCategory,
          productExisting: true,
          productImages: [
            {
              id: uuidV4(),
              imageFile,
              imageFileName
            }
          ]
        })
      };
    },
    state
  );

score:0

import produce from 'immer';

...
return {
  ...state,
  products: produce(state.products, draftProducts => {
    const product = findProductWithProductCode(draftProducts, action.payload.productCode);
    product.productImages.push(...action.payload.productImages)
  })
};

Related Query

More Query from same tag