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:
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.