Last active
August 4, 2017 18:53
-
-
Save bultas/43e861665a19e267fed7e5e724db8d4a to your computer and use it in GitHub Desktop.
Form in Redux
This file contains hidden or 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
import { connect } from 'react-redux'; | |
import { formsReducer, FormsActions, convertFormData, haveFormDataError } from 'forms'; | |
const FORMS_REDUCER_ID = 'forms'; | |
const store = createStore(formsReducer); | |
const dispach = store.dispach; | |
const FORM_ID = 'canBeDynamicID'; | |
const initialData = { | |
name: 'John', | |
age: 45, | |
additional: { | |
hair: 'brown', | |
height: 185 | |
} | |
}; | |
const scheme = { | |
type: 'object', | |
properties: { | |
name: { | |
type: 'string' | |
}, | |
age: { | |
type: 'integer' | |
}, | |
additional: { | |
type: "object", | |
properties: { | |
hair: { type: "string" }, | |
height: { type: "integer" } | |
} | |
}, | |
}, | |
required: ['name', 'age'] | |
}; | |
dispach( | |
FormsActions.createForm(FORM_ID, scheme) | |
); | |
dispach( | |
FormsActions.initFormData(FORM_ID, initialData) | |
); | |
const Input = ({ result, onChange }) => { | |
if (haveFormDataError(result)) { | |
return <red />; | |
} | |
return ( | |
<input | |
value={convertFormData(result)} | |
onChange={(e) => onChange(e.target.result)} | |
/> | |
); | |
}; | |
const Component = (props) => { | |
const formData = props[FORM_ID]; | |
const { name, additional: { hair } } = formData; // will be all results | |
return ( | |
<div> | |
<h1>{ `Your name is ${convertFormData(name)}` }</h1> | |
<label>Your name</label> | |
<Input | |
result={name} | |
onChange={(value) => { | |
dispach( | |
FormsActions.updateFormData(FORM_ID, { | |
name: value | |
}) | |
); | |
}} | |
/> | |
<label>Your hair color</label> | |
<Input | |
result={hair} | |
onChange={(value) => { | |
dispach( | |
FormsActions.updateFormData(FORM_ID, { | |
additional: { | |
hair: value | |
} | |
}) | |
); | |
}} | |
/> | |
</div> | |
); | |
}; | |
export default connect( | |
(state) => ({ | |
[FORM_ID]: state[FORMS_REDUCER_ID][FORM_ID] | |
}), | |
Component | |
); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment