In my reduce method I am trying to set the externalUrl prop, is the condition is met, however, I get the error:
Error: Invariant failed: A state mutation was detected between dispatches, in the path ‘homeScreen.dynamicHeroCarousel.0.externalUrl’.
const filteredCarouselItems = allCarouselItems?.reduce(
(acc, carouselItem) => {
if (carouselItem.cardType === 'mobileMechanic') {
const url = carouselItem.externalUrl
?.replace('{vrn}', smrDetails?.vrn?.toString() || '')
.replace('{postCode}', smrDetails?.postCode?.toString() || '');
carouselItem.externalUrl = url;
}
return [...acc, carouselItem];
},
[] as CarouselItem[],
);
>Solution :
You are mutating the state by reassigning the url.
carouselItem.externalUrl = url; // mutating the object
To fix it, You have to construct a new object instead of mutating the existing one.
const newCarouselItem = { ...carouselItem, externalUrl: url };
Then return the new object.
return [...acc, newCarouselItem];