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

Specify initial value of reducer #105

Closed
klimashkin opened this issue Feb 21, 2018 · 6 comments
Closed

Specify initial value of reducer #105

klimashkin opened this issue Feb 21, 2018 · 6 comments

Comments

@klimashkin
Copy link

Hello!

Sorry if it's been discussed or documented, but I could not find solution.
How to specify initial value of reducer in case of currying?

If on first @@redux/INIT run I don't do anything with draft, redux complains about returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state.. But if I do

some: produce((draft, action) => {
    if (draft === undefined) {
      return {};
    }
}

redux throw the same error...
Using version 1.1.0, and I though that returning object from producers should already work, strange.

@mweststrate
Copy link
Collaborator

mweststrate commented Feb 21, 2018 via email

@klimashkin
Copy link
Author

klimashkin commented Feb 21, 2018

Created simple pen where returning from currying doesn't work:
https://codesandbox.io/s/yq7q3y857v

I found in the doc:

One think to keep in mind; you cannot use this construction to initialize an uninitialized state. E.g. draft = {} doesn't do anything useful.

Seems like the only way is to pass initial value on store startup, but it's not convenient in redux world.
What if initial value could be passed as second parameter to curry function like for array.reduce?
Like

const counter = produce((draft, action) => {  
  switch (action.type) {
    case 'INCREMENT':
      return draft.count += 1;
    case 'DECREMENT':
      return draft.count -= 1;
  }
}, {count: 0});

@mweststrate
Copy link
Collaborator

@klimashkin apologies, this was a bug in the currying! Should be fixed in 1.1.1

@mweststrate
Copy link
Collaborator

See: https://codesandbox.io/s/j4m8q25363

@klimashkin
Copy link
Author

klimashkin commented Feb 22, 2018

Thanks @mweststrate!

What do you think about setting default value as a second parameter of curried produce? In redux we have to have default value for every reducer, writing if (draft === undefined) seems a little verbose

@mweststrate
Copy link
Collaborator

@klimashkin could you open a separate issue for that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants