Jeremy Bunn
Jeremy Bunn

Reputation: 671

Easy Way To Access change() from redux-form in react-admin?

I have a need to update some form data, given a selection that is made.

I would like to do this in the onChange handler of a select field using the change() function from redux-form.

Is there a way to access the redux-form change function easily using standard react-admin?

I tried picking it up from props, but it is not there;

const { change } = this.props;
console.log(change); // undefined

Upvotes: 2

Views: 1545

Answers (1)

Armando
Armando

Reputation: 51

I'm not exactly sure if this is what you're looking for, but this is how I handled it in my react-admin project. I just imported change directly from redux-form, and passed it the REDUX_FORM_NAME constant from react-admin.

Imports

import { change } from 'redux-form'
import { REDUX_FORM_NAME } from 'react-admin'
import { connect } from 'react-redux'

Edit Component

<Edit>
    <SimpleForm>
        <MyCustomComponent />
    </SimpleForm>
</Edit>

MyCustomComponent should receive a record prop automatically from SimpleForm. Also, I connected it to the redux store:

export default connect(mapStateToProps)(MyCustomComponent)

I intentionally did not provide a second argment to connect so I could have access to dispatch in my component. Perhaps another way is possible, but that's what worked for me.

So now, inside MyCustomComponent, in a handleCancel handler I created for a Cancel button, I changed the fields I wanted to change. In my specific case, I wanted to reset the fields to contain the unmodified stored value for that field.

handleCancel = () => {
    const { record, dispatch } = this.props;
    dispatch(change(REDUX_FORM_NAME, 'name', record.name));
    dispatch(change(REDUX_FORM_NAME, 'description', record.description));
    dispatch(closeDetails()); // unrelated to this answer; closes a modal
}

In the code above, I reset the 'name' and 'description' fields to their original values. Hope this helps.

Upvotes: 4

Related Questions