Search code examples
redux-formadmin-on-rest

Affecting the whole record value from a CustomField in admin-on-rest


I have a Edit component in an admin-on-rest's app which internally uses ReduxForm and the code looks like this:

<Edit {...props} >
    <CustomField />
    <TextInput source="title" />
</Edit>

I am wondering how is it possible to change title from CustomField without persisting it on the on the server?


Solution

  • You can achieve such a purpose using a custom saga and dispatching the change event from redux-form. It sounds a little bit complicated told this way, but it is not in reality. :)

    First, implement custom sagas to your application:

    const customSagas = [
        MyCustomEntitySagas,
    ];
    
    const App = () => (
        <Admin customSagas={customSagas}>
            // ...
        </Admin>
    );
    

    Then, in your custom saga, just watch an action you will emit from your CustomField, something like:

    import { change } from 'redux-form';
    import { put, takeEvery } from 'redux-saga/effects';
    
    import { CUSTOM_FIELD_CHANGE } from './actions';
    
    export function* watchForCustomFieldChange({ payload }) {
        yield put(change('form-record', 'title', payload.newTitle));
    }
    
    export default function* root() {
        yield [
            takeEvery(CUSTOM_FIELD_CHANGE, watchForCustomFieldChange),
        ];
    }
    

    For instance, here is an action creator you may want to dispatch:

    export const CUSTOM_FIELD_CHANGE = 'CUSTOM_FIELD_CHANGE';
    
    export const customFieldChange = (newTitle) => ({
        type: CUSTOM_FIELD_CHANGE,
        payload: { newTitle },
    });
    

    The key here is the Redux Sagas. Seems a like a lot of boilerplate, but it really eases the development in final.

    I tried to be as shortest as possible to prevent from too much noise. But feel free to ask if you need more informations. :)