Today I Learned

Debug draft state in redux-toolkit (immer.js)

When using console.log or debugger to display draftState in redux-toolkit reducer we normally get Immer.js proxy object which contains lots of unnecessary information. (Immer.js is used by redux-toolkit by default)

    <ref *1> {
      type_: 0,
      scope_: {
        drafts_: [ [Circular *1], [Object], [Object] ],
        parent_: undefined,
        canAutoFreeze_: true,
        unfinalizedDrafts_: 0
      },
      modified_: true,
      finalized_: false,
      assigned_: {},
      parent_: undefined,
      base_: {
        effects: {
          createEnrollmentBatch: [Object],
          updateEnrollmentBatch: [Object],
          deleteEnrollmentBatch: [Object],
          loadEnrollmentList: [Object]
        },
        enrollmentsByQstreamId: {},
        companyEnrollmentStausByQstreamId: {}
      },
      draft_: [Circular *1],
      revoke_: [Function (anonymous)],
      isManual_: false
      // and many more
    }

To display the actual data use current function imported from @redux/toolkit

import { createSlice, current } from '@reduxjs/toolkit'
...
console.log(current(draftState))

In the log output we’ll see only our data.

    {
      effects: {
        createEnrollmentBatch: { results: [], status: 'NOT_BATCHING', isEnrollMe: null },
        updateEnrollmentBatch: { results: [], suspended: null, status: 'NOT_BATCHING' },
        deleteEnrollmentBatch: { results: [], status: 'NOT_BATCHING' },
        loadEnrollmentList: { status: 'LOAD_SUCCESSFUL', error: false }
      },
      enrollmentsByQstreamId: { '3': {} },
      companyEnrollmentStausByQstreamId: {}
    }

DOCUMENTATION