Skip to main content

Initialize with existing values

Sometimes we want to initialize the form with existing values from a service call, like when doing an update operation.

export interface IPaymentMethod {  ID: number;  Name: string;  Code: string;}
export const PaymentMethodForm = () => {  const intl = useIntl();
  // Get existing values from state  const paymentMethod = useRecoilValue(getPaymentMethodState.response);
  // Initial form values when loading the form. Pass the existing values here  const initialValues = useMemo(    () => ({      ID: paymentMethod?.ID,      Name: paymentMethod?.Name,      Code: paymentMethod?.Code,    }),    [paymentMethod],  );
  // Callback to save the form values in the backend and a loading state which indicates that a save is in progress  const { savePaymentMethod, isSaveLoading } = useAddPaymentMethod();
  return (    <Card>      <Formik        initialValues={initialValues}        // Makes sure that form re-initializes every time initialValues change        enableReinitialize        onSubmit={(formValues, formikHelpers) => {          savePaymentMethod(formValues);          formikHelpers.setSubmitting(false);        }}      >        {({ submitForm, isSubmitting }) => (          <>            ...            <Box>              <Grid container justify="flex-end">                <Grid item>                  <Button                    variant="contained"                    color="primary"                    isLoading={isSubmitting || isSaveLoading}                    disabled={isSubmitting || isSaveLoading}                    onClick={submitForm}                  >                    <FormattedMessage id="button.label.save" />                  </Button>                </Grid>              </Grid>            </Box>          </>        )}      </Formik>    </Card>  );};