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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With