Created
March 31, 2017 10:57
-
-
Save simenbrekken/bb6bcfc36f918430ea438f726d3e756e to your computer and use it in GitHub Desktop.
Redux Form HoC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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