[go: up one dir, main page]

Skip to content

Commit

Permalink
docs: Add referential equality to pitfalls (immerjs#731)
Browse files Browse the repository at this point in the history
Add a section about referential equality to pitfalls, with the simple 
example of using `indexOf` on a draft array to match an element.

Fixes immerjs#730
  • Loading branch information
ianstormtaylor authored Jan 11, 2021
1 parent c21a2ef commit 8fbf93c
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions docs/pitfalls.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,22 @@ produce(state, draft => {
})
})
```

### Drafts aren't referentially equal

Draft objects in Immer are wrapped in `Proxy`, so you cannot use `==` or `===` to test equality between an original object and its equivalent draft (eg. when matching a specific element in an array). Instead, you can use the `original` helper:

```javascript
const remove = produce((list, element) => {
const index = list.indexOf(element) // this won't work!
const index = original(list).indexOf(element) // do this instead
if (index > -1) list.splice(index, 1)
})

const values = [a, b, c]
remove(values, a)
```

If possible, it's recommended to perform the comparison outside the `produce` function, or to use a unique identifier property like `.id` instead, to avoid needing to use `original`.


0 comments on commit 8fbf93c

Please sign in to comment.