Home > Software engineering >  Delete Matched Id in Nested Array in Redux
Delete Matched Id in Nested Array in Redux

Time:11-26

I have a delete button that have I set some static datas. In it I passed some ids. Matched ids should be deleted when you click the button. My problem is that I can't delete any item that matched its id.

Codesandbox is here CLICK HERE

case appConstants.DELETE_IMAGE_SUCCESS:
  return {
    ...state,
    products: state.products.map((product) => ({
      ...product,
      productImages: (product.productImages ?? []).filter(
        ({ id }) => !id.includes(action.payload)
      )
    }))
  };

CodePudding user response:

The problem is in filtering function - you're confused String.prototype.includes and Array.prototype.includes.

Right way to do this is to check for productImage.id in action.payload, not vice versa:

case appConstants.DELETE_IMAGE_SUCCESS:
  return {
    ...state,
    products: state.products.map((product) => ({
      ...product,
      productImages: (product.productImages ?? []).filter(
        ({ id }) => !action.payload.includes(id)
      )
    }))
  };

String.prototype.includes and Array.prototype.includes work in the similar way, but have different APIs - first accepts string as argument, second - Array.

  • Related