Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array reduce error – A state mutation was detected between dispatches, in the path 'homeScreen.dynamicHeroCarousel.0.externalUrl'

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[],
  );

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading