0

I am using immer.js to perform operations on arrays in the state.

Arrays: basicRecipe and recipeBasicRecipe.

I am modifying the draft.basicRecipe in the produce function. My objective is to return the updated "draft.basicRecipe" value and store the same in temparray1.

    let temparray1 = produce(state, draft => {
      
      draft.basicRecipe = draft.basicRecipe.map(item => {
        let element = draft.recipeBasicRecipes.find(e => e._id === item._id);
        console.log(element);
        if (element) {
          item.details = item.details.map(e => {
            let detail = element.details.find(d => d._id === e._id);
            if (detail) {
              e.rate = detail.rate;
            }
            return e;
          });
        }
        return item;
      });
      return draft.basicRecipe;
    });

    console.log(temparray1);

When I return the draft I am able to see updated basicRecipe nested in output. I am getting the below error when I try to return the array i.e draft.basicRecipe

 [Immer] An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft

1 Answers1

-1

This code is a mess. You are using map which returns a new array but you're also trying to mutate the original draft object.

This is still unreadable and confusing, but at least by using forEach instead of map we are just mutating and not trying to do two things at once.

let temparray1 = produce(state, (draft) => {
  draft.basicRecipe.forEach((item) => {
    let element = draft.recipeBasicRecipes.find((e) => e._id === item._id);
    if (element) {
      item.details.forEach((e) => {
        let detail = element.details.find((d) => d._id === e._id);
        if (detail) {
          e.rate = detail.rate;
        }
      });
    }
  });
});
Linda Paiste
  • 38,446
  • 6
  • 64
  • 102