Search code examples
javascriptreactjsreduxreact-reduxredux-form

Update initialValues in redux-form asyncronously without using redux


The examples in the documentation show only how to update initialValues with redux state (see http://redux-form.com/6.0.0-alpha.4/examples/initializeFromState/). I don't want to use redux because it's really messy for the application I'm building. I'd rather use component state.

I've tried using an async self-executing function in the redux-form connector, but that didn't work:

ApplicationNewForm = reduxForm({
    form: 'appapp',
    returnRejectedSubmitPromise: true,
    initialValues: (async function() { ... }()),
    handleSubmit
})(ApplicationNewForm)

that didn't work (that one should be obvious why, the component doesn't care if the assignment is async...)...

I also tried making the api call in an async componentDidMount and using this.state to set the value prop of my <Field />'s.

In each case the values don't seem to make it to the redux store, and so don't update the values in the fields.

Any ideas?

EDIT: The solution is to manually call this.props.initialize in the async componentDidMount with the data from the api call. This DOES work:

async componentDidMount() {
    try {
        const res = await axios.get('/my/user/api/')
        const { data: user } = res

        this.props.initialize({...user})
    } catch(err) {}
}

Solution

  • As of the current version, v6.5.0, the initialValues config parameter takes an object, not an async function. That might be messing with your call to this.props.initialize(). Are you seeing the INITIALIZE action being dispatched?