0

Sandbox: https://codesandbox.io/s/ucjrx?file=/src/features/todos/todosSlice.js

In todoSlice.js, at line 14, when I try to do console.log, it is printed as a revoked proxy (browser console). But when I put a breakpoint in chrome dev tools and go through that line step by step, it is not a revoked proxy. Why is this happening?

1 Answers1

1

In a RTK reducer, your state is wrapped in a Proxy object by the immer library to detect modifications. After the reducer is finished, that proxy object is revoked to prevent memory leaks.

Unfortunately, console.log does not log a in-time snapshot of an object, but a reference - and the time you try to actually explore these contents, it's already revoked.

As the documentation explains, you should log draft state values using the current export from immer that is re-exported from RTK:

import { createSlice, current } from '@reduxjs/toolkit'

const slice = createSlice({
  name: 'todos',
  initialState: [{ id: 1, title: 'Example todo' }],
  reducers: {
    addTodo: (state, action) => {
      console.log('before', current(state))
      state.push(action.payload)
      console.log('after', current(state))
    },
  },
})
phry
  • 35,762
  • 5
  • 67
  • 81
  • Just when I thought redux could not get more abstract and over-engineered. Front-end dev has become a nightmare with all of these tools that solve 1 problem and create dozens new ones. – Organic Jul 28 '22 at 11:43
  • @Organic That has nothing to do with Redux, but with how browsers are logging things. Benefit of the thing: you just write 1/4 of the code compared to legacy Redux. Also, this "problem" is shared by lots of state management libraries that use abstractions like this. – phry Jul 28 '22 at 11:56
  • 1
    @Organic Couldn't agree more. – Cherna Jul 30 '22 at 17:12