lelandrichardson / redux-pack

Sensible promise handling and middleware for redux
MIT License
1.33k stars 60 forks source link

Use-case of having the previous state in handlers params #70

Closed nilscox closed 6 years ago

nilscox commented 6 years ago

Hi,

The handler functions provided to handle always take the previous state as their only parameter. I feel that I might be misunderstanding something here, can't I use the state from the reducer's first parameter instead?

Thanks!

djkirby commented 6 years ago

Good question, I was wondering the same and had to look into it more. I think the reason is because the finish and always hooks are run after success and failure. You can see for LIFECYCLE.SUCCESS the initial state is run through the success handler and then the result of that is run through the finish handler and then the result of that is run through the always handler. https://github.com/lelandrichardson/redux-pack/blob/master/src/handle.js#L66

It also helps that you can extract the handlers as pure functions of state => state.

edit: not tested but I think this is why you should use prevState instead of the reducer state

return handle(state = {
  loading: false,
  error: null,
  data: null,
  madeTheRequest: false
}, action, {
  start: () => ({ ...state, loading: true, error: false, data: null }),
  finish: () => ({ ...state, loading: false }),
  failure: () => ({ ...state, error: true }),
  success: () => ({ ...state, data: 1 }),
  always: () => ({ ...state, madeTheRequest: true })
});

start ->
  { loading: true, error: null, data: null, madeTheRequest: false }

success ->
  { loading: true, error: null, data: null, madeTheRequest: true }

  ^^ lost what success and finish did
nilscox commented 6 years ago

Right, that makes perfectly sense to me. Thanks for sharing!