Skip to content

Instantly share code, notes, and snippets.

@aghull
Created September 6, 2017 12:25
Show Gist options
  • Save aghull/52ef115a84dc76d0c908aca4cc00bf8d to your computer and use it in GitHub Desktop.
Save aghull/52ef115a84dc76d0c908aca4cc00bf8d to your computer and use it in GitHub Desktop.
Form conventions
class FormContainer extends React.Component {
componentWillMount() {
this.props.fetchForm();
}
render() {
<MyForm onChange={this.props.updateForm}/>
<Submit onClick={this.props.submitForm}/>
}
}
class MyForm extends InputGroup {
render() {
return (
<Input {...inputProps('key')}>
...
);
}
}
class InputGroup extends React.Component {
inputProps = key => ({
key,
value: this.props.form[key],
onChange: v => this.handleChange({ [key]: v }),
errors: this.props.errors[key],
});
}
actions.js
const fetchForm = () => dispatch => {
dispatch({ type: 'FETCHING' });
httpClient.get().then(
response => dispatch({ type: 'FETCHED', response }),
response => dispatch({ type: 'FETCHING_ERRORED', response })
);
};
const handleSubmit = ({ form, dependencies = Dependencies }) => dispatch => {
dispatch({ type: 'VALIDATING' });
const errors = validateForm(form);
if (errors.length) {
dispatch({ type: 'REQUESTED_SUBMIT' });
httpClient.patch({ form }).then(
response => dispatch({ response, type: 'FETCHED' }),
response => dispatch({ error, type: 'SUBMITTING_ERRORED' })
);
} else {
dispatch({ type: 'VALIDATING_FAILED' });
}
};
const validateForm = form => {
const events = ['some', 'required', 'fields'].map(field => ({ field, type: form[field] ? 'CLEARED_FIELD' : 'ERRORED_FIELD' }));
events.forEach(dispatch);
return events.filter(event => event.type === actionTypes.MISSED_REQUIRED_ADDRESS_FIELD);
};
reducer.js
const initialState = Immutable.fromJS({
errors: null,
isLoading: null,
isSubmitting: null,
isSuccessful: null,
some: null,
required: null,
fields: null,
});
const reduce = (state = initialState, event) => {
switch(event.type) {
case 'FETCHING'
case 'FETCHED'
case 'FETCHING_ERRORED'
case 'VALIDATING'
case 'VALIDATING_FAILED'
case 'REQUESTED_SUBMIT'
case 'SUBMITTING_ERRORED'
case 'CLEARED_FIELD'
case 'ERRORED_FIELD'
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment