diff --git a/docs/pitfalls.md b/docs/pitfalls.md index 7f069bf7..ab308074 100644 --- a/docs/pitfalls.md +++ b/docs/pitfalls.md @@ -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`. + +