Skip to content

Instantly share code, notes, and snippets.

@simenbrekken
Created March 31, 2017 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simenbrekken/bb6bcfc36f918430ea438f726d3e756e to your computer and use it in GitHub Desktop.
Save simenbrekken/bb6bcfc36f918430ea438f726d3e756e to your computer and use it in GitHub Desktop.
Redux Form HoC
export const RESET_FORM = 'RESET_FORM'
export const SET_FORM_VALUE = 'SET_FORM_VALUE'
export const setValue = (id, name, value) => ({ type: SET_FORM_VALUE, id, name, value })
export const reset = (id, name, value) => ({ type: SET_FORM_VALUE, id })
const withForm = (stateName, id = stateName, resetOnUmount = true) => {
const composers = [
connect(state => {
form: state.forms[id],
}, {
reset: () => ({ type: RESET_FORM, id }),
setValue: (name, value) => ({ type: SET_FORM_VALUE, id, name, value }),
})
]
if (resetOnUmount) {
composers.push(
lifecycle({
componentWillUnmount() {
this.props.reset()
}
})
)
}
return composers(composers)
}
const updateForm = (state = {}, action) => {
switch (action.type) {
case SET_FORM_VALUE:
return {
...state,
[action.name]: action.value,
}
default:
return state
}
}
const updateForms = (state = {}, action) => {
switch (action.type) {
case RESET_FORM:
return omit(forms, action.id)
case SET_FORM_VALUE:
return updateForm(state[action.id], action)
default:
return state
}
}
const formReducer = (state = {}, action) => {
switch (action.type) {
case RESET_FORM:
case SET_FORM_VALUE:
return updateForms(state.forms, action)
default:
return state
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment