Zaelot-Inc / use-reducer-logger

A very basic logger for the useReducer function in the React Hooks API.
https://www.npmjs.com/package/use-reducer-logger
MIT License
94 stars 16 forks source link

pre state is wrong with object state #13

Open SilvaQ opened 3 years ago

SilvaQ commented 3 years ago

if the state is object ,logger pre state will be change ,so pre and now is the same ref.

we need to deep copy befor excute the reducer.

my code:

 (state, action) => {
      const preState = { ...state };  //  deep copy first befor consume
      const next = reducer(state, action);
      if (debug) {
        console.group(
          `%cAction【${action.type}】%cat ${getCurrentTimeFormatted()}`,
          "color: lightgreen; font-weight: bold;",
          "color: #9E9E9E; font-weight: 700;",
          "color: lightblue; font-weight: lighter;"
        );
        // 上一个state
        console.log(
          "%cPrevious State:",
          "color: #9E9E9E; font-weight: 700;",
          preState
        );
btegs commented 2 years ago

@SilvaQ and @jefflombard - I don't mean to revive an old thread, but I was interested in the project and looked at the code above. What if you installed lodash.clonedeep (this one may be outdated) or standard lodash via npm or yarn and then used that. For example:

This at the top of the file in either one of these commands:

import { cloneDeep } from 'lodash';

OR

import cloneDeep from 'lodash/cloneDeep';

Then:

 (state, action) => {
      const preState = cloneDeep(state);  //  deep copy first before consume
      const next = reducer(state, action);
      if (debug) {
        console.group(
          `%cAction【${action.type}】%cat ${getCurrentTimeFormatted()}`,
          "color: lightgreen; font-weight: bold;",
          "color: #9E9E9E; font-weight: 700;",
          "color: lightblue; font-weight: lighter;"
        );
        // 上一个state
        console.log(
          "%cPrevious State:",
          "color: #9E9E9E; font-weight: 700;",
          preState
        );

If this is something that can be done at the core of the project, you can always cherry pick lodash functions without bringing in the entire suite. :-)