Last active
February 24, 2017 01:39
-
-
Save samcorcos/c83b9b116795ccd21f945658d6001a24 to your computer and use it in GitHub Desktop.
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
// Reducer.js | |
const initialState = { | |
user: { | |
email: null, | |
name: null, | |
}, | |
myForm: { // define our form in advance | |
input1: null, | |
input2: null, | |
}, | |
} | |
const Reducer = (state = initialState, action) => { | |
switch (action.type) { | |
case 'UPDATE_FORM': | |
return { | |
...state, | |
[action.payload.form]: { | |
...state[action.payload.form], | |
[action.payload.key]: action.payload.value, | |
}, | |
default: return state | |
} | |
} | |
export default Reducer | |
// Store.js | |
import { createStore, } from 'redux' | |
import Reducer from './Reducer' | |
const Store = createStore(Reducer) | |
export default Store | |
// Actions.js | |
export const updateForm = payload => ({ | |
type: 'UPDATE_FORM', | |
payload, | |
}) | |
// App.js | |
import React from 'react' | |
import { Provider, } from 'react-redux' | |
import Store from '../redux/Store' | |
import AppWrapper from './AppWrapper' | |
export const App = props => | |
<Provider store={Store}> | |
<AppWrapper /> | |
</Provider> | |
export default App | |
// AppWrapper.js | |
import React from 'react' | |
import { connect, } from 'react-redux' | |
import * as Actions from '../redux/Actions' | |
const update = (params, props) => props.updateForm(params) | |
export const AppWrapper = props => | |
<div> | |
<input | |
value={props.myForm.input1} | |
onChange={e => update({ | |
form: 'myForm', | |
key: 'input1', | |
value: e.target.value, | |
}, props)} | |
type={'text'} /> | |
<input | |
value={props.myForm.input2} | |
onChange={e => update({ | |
form: 'myForm', | |
key: 'input2', | |
value: e.target.value, | |
}, props)} | |
type={'text'} /> | |
</div> | |
const mapStateToProps = state => ({ | |
myForm: state.myForm, | |
}) | |
const mapDispatchToProps = dispatch => ({ | |
updateForm: params => dispatch(Actions.updateForm(params)), | |
}) | |
export default connect(mapStateToProps, mapDispatchToProps)(AppWrapper) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment