Search code examples
javascriptreactjsreact-adminreact-final-form

How to access form data in custom components in react-admin?


I need to change the behaviour of a toolbar button depending on a status field of the form. I don't know how to get access to the current form data to read the status value.

I tried with FormDataConsumer in the surrounding component (Toolbar in my case) and pass formData as a prop, but that had the side effect that handleSubmitWithRedirect inside the button did not work.

I'd like to read form data directly inside the button component. How can I do this?

The current code:

// ------------------------------------------------------------------------------------------
const StatusButton= ({ handleSubmitWithRedirect, ...props }) => {
    const form = useForm();

    const handleClick = useCallback(() => {
        switch (props.formdata.status.id) {   
            case 0:
                form.change('status', status[1]);
                break;
            case 1:
                form.change('status', status[2]);
                break;
            default:
        }
        handleSubmitWithRedirect('list');
    }, [form]);

    return <SaveButton {...props} handleSubmitWithRedirect={handleClick} />;
};

// ------------------------------------------------------------------------------------------
export const MyToolbar= props => (
    <Toolbar {...props} >
        <SaveButton
            label="Speichern"
            redirect="list"
            submitOnEnter={true}
            variant="text"
        />

        <FormDataConsumer>
            {({ formData, ...rest }) =>
                <StatusButton
                    label="Statuswechsel"
                    redirect="list"
                    submitOnEnter={false}
                    variant="text"
                    formdata={formData}  
                />
            }
        </FormDataConsumer>
    </Toolbar>
);

Update: you can see an example in codesandbox:

https://codesandbox.io/s/react-admin-accessformdata-v0uq7?fontsize=14&hidenavigation=1&initialpath=%23%2Fposts%2F1%2Fshow&module=%2Fsrc%2Fposts%2FPostShow.js&theme=dark


Solution

  • The field values of the current form can be read accessed this:

    import { useForm } from 'react-final-form';
    
    const form = useForm();
    var formdata = form.getState().values;
    

    formdata contains the whole form values as an object.