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

Why the extra ...state in the action map? #56

Closed
0x80 opened this issue Jan 10, 2016 · 2 comments
Closed

Why the extra ...state in the action map? #56

0x80 opened this issue Jan 10, 2016 · 2 comments

Comments

@0x80
Copy link

0x80 commented Jan 10, 2016

I am wondering why we are required to merge in the current state in every reducer function.

const initialState = {
  selectedTagIds: [],
  tags: getTagsForLanguage('en')
}

const reducer = handleActions({
  [ADD_FILTER_TAG]: (state, { payload }) => ({ ...state, selectedTagIds: [...state.selectedTagIds, payload] }),
  [REMOVE_FILTER_TAG]: (state, { payload }) => ({ ...state, selectedTagIds: state.selectedTagIds.filter(id => id !== payload) }),
  [CLEAR_FILTER]: (state) => ({ ...state, selectedTagIds: [] }),
}, initialState)

If handleActions was something like...

function handleActions(actionsMap, initialState) {
  return (state = initialState, action) => {
    const reduceFn = actionsMap[action.type]
    if (reduceFn) {
      return {...state, ...reduceFn(state, action)}
    }

    return state
  }
}

... you could write

const reducer = handleActions({
  [ADD_FILTER_TAG]: (state, { payload }) => ({ selectedTagIds: [...state.selectedTagIds, payload] }),
  [REMOVE_FILTER_TAG]: (state, { payload }) => ({ selectedTagIds: state.selectedTagIds.filter(id => id !== payload) }),
  [CLEAR_FILTER]: (state) => ({ selectedTagIds: [] }),
}, initialState)

It makes it less verbose and harder to mess up imho

@acdlite
Copy link
Contributor

acdlite commented Jan 10, 2016

Thanks for the suggestion! However, what if is state is not a plain object — what if it's an array, or an Immutable Map? Or just a number?

What if, depending on the content of the payload, we want to return the previous state (and maintain the same object reference?

Merging state every time, while similar to what React does with setState(), is against the spirit of Redux and makes too many restrictive assumptions.

@acdlite acdlite closed this as completed Jan 10, 2016
@0x80
Copy link
Author

0x80 commented Jan 10, 2016

Makes sense 😄 Thanks for clarifying this decision 👍

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