mardi 12 janvier 2021

Antd 4 Checkbox doesn't have value after form submit

What I have

I have an Ant Design 4 form with a checkbox in it:

const Example = ({ initialValues, onSave }) => {
  const [form] = Form.useForm();

  useEffect(() => {
    form.resetFields();
  }, [initialValues.isAccepted]);

  const onFinish = (values) => {
    console.log(values);
    onSave(values);
  };

  const getInitialValues = useCallback(() => ({
    isAccepted: initialValues.isAccepted || false,
  }));

  return (
    <Form form={form} onFinish={onFinish} initialValues={getInitialValues()}>
      <Form.Item name="isAccepted">
        <Checkbox>The company can use my data</Checkbox>
      </Form.Item>
      <Button type="primary" htmlType="submit">Save</Button>
    </Form>
  );
};

Problem

The checkbox is always unchecked even if it is true inside initialValues. Also, when I submit the form the values variable always contains the value from initialValues, it doesn't registers that I changed (checked or unchecked) the checkbox.

Goal

I would like the initial value to be set properly from inititalValues and get the current value of the checkbox in onFinish.




Aucun commentaire:

Enregistrer un commentaire