23

I'm using immer in a react app to handle state changes. Let's say the state didn't change as I expected, so I'd want to debug it, but both console.log and debugger gives a Proxy object which doesn't contain any useful information, e.g. what is the state at that time.

Example code to get the new state:

return immer(state, draftState => {
    // Some mutations here, didn't go as expected
    console.log(draftState.blah) // Gives 'Proxy' object
    debugger // Same deal
  })

How can I debug my code?

Stanley Luo
  • 3,689
  • 5
  • 34
  • 64

4 Answers4

29

Immer 7+ has current() for this purpose. So, you can do this:

import { current } from 'immer';

console.log(current(draft));

Official documentation and test

prnsml
  • 2,332
  • 17
  • 18
  • Yes but you cannot do that using a breakpoint based debugger, that's equivalent to using a console.log – Eric Burel Oct 28 '21 at 12:19
  • 1
    @EricBurel Why not? Add breakpoint and then add a watcher to check the value. You need to check how immer module is imported and under what name it is available in the current context and then you can create the watcher. For example in create-react-app type of project watcher would look similar to this: `immer__WEBPACK_IMPORTED_MODULE_1__.current(draft)` – prnsml Oct 28 '21 at 20:35
  • I did not know about watcher, I'll dig that, thank you! – Eric Burel Nov 08 '21 at 08:39
21

If you serialize / de-serialize the draft, the output will be a plain JavaScript object and will appear as such in the console.

console.log(JSON.parse(JSON.stringify(draft)))
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Dave
  • 1,196
  • 15
  • 22
9

Turns out you just need to dig in in chrome dev tools - e.g. if you are using the debugger, then on the right-side panel you can click into Scope -> Local -> searchTarget -> [[Target]] -> base/draft, where you can see the actual values.

Stanley Luo
  • 3,689
  • 5
  • 34
  • 64
  • 1
    The current version of Immer puts the actual value under the `[[Target]] -> t ` property (I'm not sure where you see base/draft). Either way, thanks! I never saw that before. – TetraDev Oct 21 '20 at 18:21
  • If you want to inspect the object further in the console, you can right click on the value and say 'Store as global' which will give you `temp1` you can then use in the console – Simon_Weaver Sep 19 '21 at 22:38
2

For anyone else that is coming across this and is confused as to how to find the Scope -> Local -> searchTarget -> [[Target]] -> base/draft make sure that you set the debugger. Once that's set, you'll see the right-side panel of the Sources tab with the relevant info:

enter image description here

Ariel Salem
  • 357
  • 3
  • 12