Initialize From State Form - rkaku/react-hooks-101 GitHub Wiki
store.js
import{createStore,combineReducers}from'redux';import{reducerasreduxFormReducer}from'redux-form';importaccountfrom'./account';constreducer=combineReducers({
account,form: reduxFormReducer,// mounted under "form"});conststore=(window.devToolsExtension
? window.devToolsExtension()(createStore)
: createStore)(reducer);exportdefaultstore;
account.js
constLOAD='redux-form-examples/account/LOAD';constreducer=(state={},action)=>{switch(action.type){caseLOAD:
return{data: action.data,};default:
returnstate;}};/** * Simulates data loaded into this reducer from somewhere */exportconstloadCreator=data=>({type: LOAD, data });exportdefaultreducer;
Initialize From State Form
importReactfrom'react';import{connect}from'react-redux';import{Field,reduxForm}from'redux-form';import{loadCreator}from'./account';constdata={// used to populate "account" reducer when "Load" is clickedfirstName: 'Jane',};
// Decorate with reduxForm(). It will read the initialValues prop provided by connect()InitializeFromStateForm=reduxForm({form: 'initializeFromState',// a unique identifier for this form})(InitializeFromStateForm);
// You have to connect() to any reducers that you wish to connect to yourselfInitializeFromStateForm=connect(state=>({initialValues: state.account.data,// pull initial values from account reducer <- useSelector}),{load: loadCreator},// bind account loading action creator <- useDispatch)(InitializeFromStateForm);