Home > Net >  Formik Default Values UseEffect
Formik Default Values UseEffect

Time:12-29

I am trying to prepopulate a Formik with JSON data. The data appears fine and it is returned. I have two issues.

I am using ASP.NET Core as the back end. Should I use values or initialValues as the variable? When I use initialValues, I get assign fields. The labels are still populated.

The labels are still populated, after I send a default value. All the fields are read only and I cannot edit them:

enter image description here

Here is my code:

function OrdersToReporting() {

    const [initialValues, setInitialValues] = useState<OrdersToReportingViewModels>({ });

    useEffect(() => {
        agent.Settings.getOrdersSettings().then((userList) => {
            let solutionName = (new URLSearchParams(window.location.search)).get("SolutionName");
            let solutionWebsite = (new URLSearchParams(window.location.search)).get("SolutionWebsite");
            userList.data.SolutionName = solutionName;
            userList.data.SolutionWebsite = solutionWebsite;
            setInitialValues(userList.data);
        });
    }, []);

    const handleSubmit = async (
        values: any,
        { resetForm, setErrors, setStatus, setSubmitting }: any
    ) => {
        try {
            await timeOut(1500);
            agent.Settings.saveOrdersSettings(values);
            resetForm();
            setStatus({ sent: true });
            setSubmitting(false);
        } catch (error: any) {
            setStatus({ sent: false });
            setErrors({ submit: error.message });
            setSubmitting(false);
        }
    };

    return (
        <Formik
            initialValues={initialValues}
            validationSchema={validationSchema}
            onSubmit={handleSubmit}
        >
            {({
                errors,
                handleBlur,
                handleChange,
                handleSubmit,
                isSubmitting,
                touched,
                values,
                status,
            }) => (
               
                        {isSubmitting ? (
                            <Box display="flex" justifyContent="center" my={6}>
                                <CircularProgress />
                            </Box>
                        ) : (
                            <form onSubmit={handleSubmit}>
                                <Grid container spacing={6}>
                                        <Grid item md={6}>
                                            <TextField
                                                name="SolutionName"
                                                label="Solution Name"
                                                value={initialValues.SolutionName}
                                                fullWidth
                                                onBlur={handleBlur}
                                                onChange={handleChange}
                                                variant="outlined"
                                                my={2}
                                            />

                                            <TextField
                                                name="SolutionWebsite"
                                                label="Solution Website"
                                                value={initialValues.SolutionWebsite}
                                                fullWidth
                                                onBlur={handleBlur}
                                                onChange={handleChange}
                                                variant="outlined"
                                                my={2}
                                            />

                                        <TextField
                                            name="lastDownloadUtc"
                                            label="Last Download Date Start"
                                                value={initialValues.LastDownloadUtc}
                                            fullWidth
                                            onBlur={handleBlur}
                                            onChange={handleChange}
                                            variant="outlined"
                                            my={2}
                                        />
                                    </Grid>
                                    <Grid item md={6}>
                                            <TextField
                                                name="lastDownloadUtcEnd"
                                                label="Last Download Date End"
                                                value={initialValues.LastDownloadUtcEnd}
                                                fullWidth
                                                onBlur={handleBlur}
                                                onChange={handleChange}
                                                variant="outlined"
                                                my={2}
                                            />
                                    </Grid>
                                </Grid>

                             

                                <Button
                                    type="submit"
                                    variant="contained"
                                    color="primary"
                                    mt={3}
                                >
                                    Save changes
                                </Button>
                            </form>
                        )}
                  
            )}
        </Formik>
    );
}

CodePudding user response:

For your questions,

  1. You should use initialValues to assign default values to your fields.

    since you are getting the data from some function, there might be a delay in setting initialValues. So pass enableReinitialize={true} in formik props.

  2. You were not able to change the values because you set

    value={initialValues.fieldName} // always value will be this unless you change initialValues state
    

    for every textfield. Always this will be same even if you edit.

    Just remove the value property formik will handle it by default.

  • Related