I've spent so long thinking about immutable ways to update objects and arrays that I had trouble wrapping my head around using mutating methods again, as is needed with immer.
It would've helped me get started faster if simple "best practice" examples similar to these were included in the docs:
import produce from "immer";
// object mutations
const todosObj = {
id1: { done: false, body: "Take out the trash" },
id2: { done: false, body: "Check Email" }
};
// add
const addedTodosObj = produce(todosObj, draft => {
draft["id3"] = { done: false, body: "Buy bananas" };
});
// delete
const deletedTodosObj = produce(todosObj, draft => {
delete draft["id1"];
});
// update
const updatedTodosObj = produce(todosObj, draft => {
draft["id1"].done = true;
});
// array mutations
const todosArray = [
{ id: "id1", done: false, body: "Take out the trash" },
{ id: "id2", done: false, body: "Check Email" }
];
// add
const addedTodosArray = produce(todosArray, draft => {
draft.push({ id: "id3", done: false, body: "Buy bananas" });
});
// delete
const deletedTodosArray = produce(todosArray, draft => {
draft.splice(draft.findIndex(todo => todo.id === "id1"), 1);
});
// update
const updatedTodosArray = produce(todosArray, draft => {
draft[draft.findIndex(todo => todo.id === "id1")].done = true;
});
...though I'm not positive draft.splice(draft.findIndex(todo => todo.id === "id1"), 1) is the best way to delete an item from an array mutably. This is a case where the immutable draft.filter(todo => todo.id !== "id1") seems less verbose.
Note that return draft.filter(todo => todo.id !== "id1") will work as well :) The findIndex will be more efficient though. But for efficiency reasons, I generally recommend not to store id-ed objects in an array in the first place. Will copy the section to the readme
Added, closing
In your examples, the delete of an element from array will fail if findIndex doesn't find any element. You will then remove element from the end of the array which is not the desired result.
@mweststrate The examples are gone now. Please consider adding them to the documentation. The docs are very lacking in their current state.
One thing I'm not sure of: do deletes in nested arrays work within producer? It'd be great if the usage patterns gave an example for nested arrays. I'm not having any issues with Map, just arrays.
I keep getting this error:
Immer drafts cannot have computed properties
Given a state like this:
{
positions: [ [1] ]
}
I want to delete [1], so that positions is an empty array ([]), producing the following state:
{
positions: []
}
I've tried several variations of deleting objects from an array but I keep getting the same error:
Immer drafts cannot have computed properties
Example code:
const deletePosition = produce((schema, {id}) => {
for (const row of schema.positions) {
if (isArray(row)) {
let index = row.indexOf(id);
if (index > -1) {
row.splice(index, 1);
}
if (isEmpty(row)) {
schema.positions.splice(schema.positions.indexOf(row), 1);
}
}
}
})
I also tried:
mapBut, it still results in the same error.
Amazing
Is there any best practice for updating sub-items?
eg:
// object mutations
const todosObj = {
id1: { done: false, body: "Take out the trash", item1: 1, item2: 2 },
id2: { done: false, body: "Check Email", item1: 1, item2: 2 }
};
// update
const newData = {item1: 3, item2: 4}
const updatedTodosArray = produce(todosArray, draft => {
const oldData = draft[draft.findIndex(todo => todo.id === "id1")];
draft[draft.findIndex(todo => todo.id === "id1")] = {...oldData, ...newData}
});
yes, if you need a spread in immer, you are probably missing the point :)
const item = draft.find(todo => todo.id === "id1");
Object.assign(item, newData)
sorry, that came out wrong :'). What I wanted to point at, if you need a spread, that is generally a good flag that it can probably expressed in a simpler way when using immer.
Pleaaaasee add this 👍 👍 👍
Sorry for ignoring this issue so long, it always bungled at the end of my to-do list. There is now a dedicated page again for mutable updates! https://immerjs.github.io/immer/docs/update-patterns
import produce, {original} from "immer"; or import {original, produce} from "immer" // docs shows both, ???
// delete (if order of array doesn't matter)
const deletedTodosArray = produce(todosArray, draft => {
const data= original(draft); // for large data sets
const index = data.findIndex(todo => todo.id === "id1");
draft[index] = draft[data.length - 1]; // much faster than splice
draft.pop();
});
Both are valid
On Thu, 25 Jun 2020, 19:02 Chirantha Dulanjala, notifications@github.com
wrote:
import produce, {original} from "immer"; or import {original, produce} from "immer" // docs shows both, ???
// delete (if order of array doesn't matter)
const deletedTodosArray = produce(todosArray, draft => {
const data= original(draft); // for large data sets
const index = data.findIndex(todo => todo.id === "id1");
draft[index] = draft[data.length - 1]; // much faster than splice
draft.pop();
});—
You are receiving this because you modified the open/close state.
Reply to this email directly, view it on GitHub
https://github.com/immerjs/immer/issues/115#issuecomment-649734141, or
unsubscribe
https://github.com/notifications/unsubscribe-auth/AAN4NBBXKDINXUJLRERMIBTRYOGMRANCNFSM4ETFQP7Q
.
does .map should work?
Please refrain from comment on closed issues.
Most helpful comment
@mweststrate The examples are gone now. Please consider adding them to the documentation. The docs are very lacking in their current state.