Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I see state when logging to the console instead of Proxy object inside reducer action?

When using console.log() inside a reducer action, the state prints as a Proxy object, instead of the object I actually want to see. How do I see the actual object? I am using redux-starter-kit createSlice, I am not sure if this has anything to do with it.

import { createSlice } from "redux-starter-kit";

export interface IToDo {
    id: number;
    name: string;
    complete: boolean;
}

const initialState: IToDo[] = [
    {
        id: 1,
        name: 'Read a bit',
        complete: true
    }
];

const { actions, reducer } = createSlice({
    slice: "todos",
    initialState,
    reducers: {
        toggleTodo(state: IToDo[], action) {
            const todo = state.find(todo => todo.id === action.payload);
            console.log(todo);
            if (todo) {
                todo.complete = !todo.complete;
            }
        }
    }
})

export const toDosReducer = reducer;
export const { toggleTodo } = actions;

This is the output I see in the console when I toggle my ToDo:

Console output

like image 549
sutherlandahoy Avatar asked Jul 28 '19 11:07

sutherlandahoy


2 Answers

Redux toolkit includes the immer current function specifically for this purpose. You can call:

console.log(current(state)) 

Per the redux toolkit docs,

The current function from the immer library, which takes a snapshot of the current state of a draft and finalizes it (but without freezing). Current is a great utility to print the current state during debugging, and the output of current can also be safely leaked outside the producer.

There is additional information in the immer docs.

like image 192
Linda Paiste Avatar answered Sep 19 '22 19:09

Linda Paiste


You can convert your object to string with number of indentions, check the code bellow:

JSON.stringify(state, undefined, 2) 

It returns something like this

// {  //   "firName: "..." //   "lastName": '...',      //   ...  // } 
like image 43
Purkhalo Alex Avatar answered Sep 21 '22 19:09

Purkhalo Alex