Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't make filter work with Immer.js to remove nested object in array

I'm starting with Immer.js for immutability in JS and I can't find a way to remove an object in an array using the filter method. It returns the same object. BTW, I'm doing it in React with state but to make it more straightforward I made up simple snippets that reflect my problem.

const sampleArr = [
      {
        items: [
          { slug: "prod1", qnty: 1 },
          { slug: "prod2", qnty: 3 },
          { slug: "prod3", qnty: 2 },
        ],
      },
    ];
    
    const newState = produce(sampleArr, (draft) => {
      draft[0].items.filter((item) => item.slug !== "prod1");
    });
    
    console.log(newState);

Console.log was supposed to give me the same whole array but without the first item. However, what I get is the same array without any change.

I googled it and searched on immer docs but couldn't find my answer. Immer.js docs about Array mutation => https://immerjs.github.io/immer/docs/update-patterns

Obs. To test it out on chrome dev tools you can copy-paste the immer lib (https://unpkg.com/[email protected]/dist/immer.umd.production.min.js) and change produce method to immer.produce

like image 643
Gabriel Linassi Avatar asked Jun 30 '26 10:06

Gabriel Linassi


1 Answers

Using destructuring for making immutable objects goes against Immert. The way of solving this issue is by reassigning the filtered part to draft. The solution looks like this:

const sampleArr = [
  {
    items: [
      { slug: "prod1", qnty: 1 },
      { slug: "prod2", qnty: 3 },
      { slug: "prod3", qnty: 2 },
    ],
  },
];

const newState = produce(sampleArr, (draft) => {
  draft[0].items = draft[0].items.filter((item) => item.slug !== "prod1");
});

You can play around in the repleit here: https://replit.com/@GaborOttlik/stackoverflow-immer#index.js

like image 190
Gábor Ottlik Avatar answered Jul 03 '26 00:07

Gábor Ottlik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!