I'm probably missing something from the docs, but how do I prepopulate a form? Say I have a dialog that pops up with a form in it, and I have a few fields I'm passing as props to the form, and but I also want rrf in Redux to also be aware of the default values.
In normal Redux, you would "prepopulate" a model with an initialState in your reducer. React Redux Form works the same way, by providing the initialState as the second argument to the reducer creator:
import { modelReducer } from 'react-redux-form';
const initialUserState = {
firstName: '',
lastName: ''
};
const userReducer = modelReducer('user', initialUserState);
export default userReducer;
All the fields will be prepopulated, using defaultValue (if you're using <Field>). Hope that helps!
This happens way after the creation of the Redux store and any reducers, though. To give more context, imagine a list of items, each with an edit button. Clicking edit for any particular item pops up a Material UI <Dialog> which contains a form, and that form is pre-filled with the item's existing data. But those form fields have to be linked with rrf.
I feel like I'd need to have some sort of dispatch that updates several fields at once, something I can call in componentDidMount.
Sure, you can do that with actions.merge(model, object).
Thanks!
Hi there,
I have a similar issue although I'm trying to pre-populate a form with some data that are stored in LocalStorage after authentication. The problem I have is that the reducer doesn't get the initial data from local storage in case the user is logged out and the store is created before the localstorage gets updated with user info. haven't found a way to update the form's model so far but a little help would be appreciated! thanks
let user = JSON.parse(localStorage.getItem('user'));
const initialUserState = user ? { loggedIn: true, user } : {};
const rootReducer = combineReducers({
authentication,
registration,
alert,
...createForms({
userLogin : {},
userProfile : initialUserState
})
});
Also tried the solution above to merge data on componentDidMount but how do get the model and value to componentDidMount? thanks!!
Hope this can be helpfull but I fixed it by dispatching the action.merge actioncreator in the componentDidMount function like so:
componentDidMount(){
let user = JSON.parse(localStorage.getItem('user'));
const initialUserState = user ? { loggedIn: true, user } : {};
store.dispatch(actions.merge("userProfile", initialUserState));
}`
Most helpful comment
Hope this can be helpfull but I fixed it by dispatching the action.merge actioncreator in the componentDidMount function like so:
componentDidMount(){let user = JSON.parse(localStorage.getItem('user'));const initialUserState = user ? { loggedIn: true, user } : {};store.dispatch(actions.merge("userProfile", initialUserState));}`