davidkpiano / react-redux-form

Create forms easily in React with Redux.
https://davidkpiano.github.io/react-redux-form
MIT License
2.07k stars 251 forks source link

Set initialValue asynchronously #1110

Open djbingham opened 6 years ago

djbingham commented 6 years ago

Hi, I'm struggling with implementing a form reset button for a form that has asynchronously loaded initial values. Any pointers would be much appreciated.

I'm using a custom reducer with createForms() so that I can load initial values for my form asynchronously. My form sits inside a component whose componentWillMount method dispatches an action to load my initial data. That data is put into the store by my reducer and the form then renders with correct values.

Now I need a reset button to set the form back to the values that I loaded asynchronously. Dispatching action.reset(model) resets to empty values, since I had no initial values when instantiating the form model. I noticed in the documentation that it says actions.load(model, value) is "useful when you need to set an initial model value asynchronously". That sounds like exactly what I want, so I tried dispatching actions.load as soon as my async data load has completed. However, action.reset still empties all of my inputs because actions.load has not actually set initialValue in the store. Instead, it's set loadedValue, which seemingly is not picked up by the reset action.

Is there any way to set initialValue asynchronously so that triggering action.reset(model) will reset to my async-loaded state and not the empty initial state?

davidkpiano commented 6 years ago

Try actions.setInitial.

djbingham commented 6 years ago

Hi @davidkpiano, thanks for the suggestion but that's not working. From the documentation, it sounds like actions.setInitial is similar to actions.reset but resetting just the form field values, not the model. I want the whole model to reset, but to values that I fetched via an API call after page load rather than to the static initial values.

I need something similar to actions.load but setting .initialValue rather than .loadedValue on the model.

write2art commented 6 years ago

+1 here.

I`m loading values this way:

actions.load(model, data))
actions.setInitial(model)

Now i have my loaded values in initial values of the form state as well, but reseting the form brings back empty initial values from the store initialise.

Is it expected behaviour?

leomoreno commented 5 years ago

Absolutely +1 for adding a sample in docs about how to provide existing data fetched in a async manner so no available when creating the store. @write2art workaround works for me, but was hard to get here 😅