Skip to content

Commit 8fbf93c

Browse files
authoredJan 11, 2021
docs: Add referential equality to pitfalls (#731)
Add a section about referential equality to pitfalls, with the simple example of using `indexOf` on a draft array to match an element. Fixes #730
1 parent c21a2ef commit 8fbf93c

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
 

‎docs/pitfalls.md

+19
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,22 @@ produce(state, draft => {
7070
})
7171
})
7272
```
73+
74+
### Drafts aren't referentially equal
75+
76+
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:
77+
78+
```javascript
79+
const remove = produce((list, element) => {
80+
const index = list.indexOf(element) // this won't work!
81+
const index = original(list).indexOf(element) // do this instead
82+
if (index > -1) list.splice(index, 1)
83+
})
84+
85+
const values = [a, b, c]
86+
remove(values, a)
87+
```
88+
89+
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`.
90+
91+

0 commit comments

Comments
 (0)
Please sign in to comment.