Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pre state is wrong with object state #13

Open
SilvaQ opened this issue Sep 7, 2021 · 1 comment
Open

pre state is wrong with object state #13

SilvaQ opened this issue Sep 7, 2021 · 1 comment
Labels
help wanted Extra attention is needed

Comments

@SilvaQ
Copy link

SilvaQ commented Sep 7, 2021

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
        );
@jefflombard jefflombard added the help wanted Extra attention is needed label Oct 16, 2021
@btegs
Copy link

btegs commented Jan 21, 2022

@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. :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

3 participants