From 0301884663caf6b8f4647420a1b600ba53e79cb4 Mon Sep 17 00:00:00 2001 From: Ian Storm Taylor Date: Thu, 7 Jan 2021 23:48:47 -0500 Subject: [PATCH] Add referential equality to pitfalls 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 --- docs/pitfalls.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/docs/pitfalls.md b/docs/pitfalls.md index 22949c8f..2f8e5370 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`. + +