Bug report - Checkbox component always undefined after page refresh

Hello,

I have a problem with:

  1. useForm from @forge/react
  2. Checkbox from @forge/react (the bug is also related for Toggle component)

When the component is first loaded on the page, the defaultValue is displayed normally in the form, but without touching this input, the value is undefined after submitting. If the form is submitted once and opened a second time, defaultValue is passed normally.

Code snippet:

export const CreateOrEditCardModal = ({setLoader}) => {
  const context = useProductContext();
  const [isOpen, setIsOpen] = useState(false);

  const openModal = () => setIsOpen(true);
  const closeModal = () => setIsOpen(false);

  const { handleSubmit, getFieldId, register, formState, getValues } = useForm({
    defaultValues: {
      active: true,
    },
  });
  
  useEffect(() => {
    console.log("getValues: ", getValues());
  }, [formState]);

  const onSubmit = (data) => {
    console.log("submit: ", data);
    invoke('setCardForCurrentUser', { data }).then(() => setLoader(a => a + 1)).then(closeModal);
  };

  return (
    <>
      <Button appearance="primary" onClick={openModal}>
        Update my card
      </Button>

      <ModalTransition>
        {isOpen && (
          <Modal onClose={closeModal}>
            <Form onSubmit={ handleSubmit(onSubmit) }>
              <ModalHeader>
                <ModalTitle>Update a card for</ModalTitle>
                <User accountId={context.accountId} />
              </ModalHeader>
              <ModalBody>
                <Stack space="space.100">
                  <Box>
                    <Label labelFor={getFieldId("active")}>Is card active?</Label>
                    <Checkbox {...register('active')} label="Active" />
                  </Box>
                </Stack>
              </ModalBody>
              <ModalFooter>
                <Button appearance="subtle" onClick={closeModal}>
                  Close
                </Button>
                <Button appearance="primary" type="submit">
                  Update
                </Button>
              </ModalFooter>
            </Form>
          </Modal>
        )}
      </ModalTransition>
    </>
  );
};

The effect:

The problem seems obvious, the checkbox component or useForm is broken in terms of defaultValues. Does anyone have a workaround?

I also noticed an issue with defaultValue in useForm. See here [FRGE-1381] - Ecosystem Jira

1 Like