Strange behviour of state in slice redux-toolkit (revoked proxy)

1k Views Asked by At

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

There are 1 best solutions below

3
On BEST ANSWER

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))
    },
  },
})