Mehdi Raza
Mehdi Raza

Reputation: 385

useFormik React - Update initialValues

I am using useFormik hook for my data handling. Adding the data is fine, but when I want to update the data in the same component I need to change the initial values to the custom object instead of having empty strings. Is there formik way of doing that with useFormik Hook? although I can achieve that with states, but then what will be the benefit of using the formik all along. Kindly help!

const formik = useFormik({
        initialValues: {
            name: '',
            post: '',
            contact: '',
            email: '',
            password: '',
        },
        onSubmit: values => {
            //handling submit
        },
    });

Form:

  <form className={classes.form} onSubmit={formik.handleSubmit}>
                    <Grid container spacing={2}>
                        <Grid item xs={12} sm={6}>
                            <TextField
                                autoComplete="name"
                                variant="outlined"
                                required
                                fullWidth
                                label="Name"
                                autoFocus
                                id="name"
                                name="name"
                                onChange={formik.handleChange}
                                value={formik.values.name}
                            />
                        </Grid>
                        <Grid item xs={12} sm={6}>
                            <TextField
                                variant="outlined"
                                required
                                fullWidth
                                label="Post"
                                autoComplete="post"
                                id="post"
                                name="post"
                                onChange={formik.handleChange}
                                value={formik.values.post}

                            />
                        </Grid>
//Submit button and form close etc

Thanks

Upvotes: 6

Views: 9042

Answers (1)

Mehdi Raza
Mehdi Raza

Reputation: 385

I found the solution that is: For One field

const editEmployee = ()=> {
    formik.setFieldValue("name","Imran");
    alert("changed")     
}

For Multiple:

formik.setValues({"name":"hey","post":"hoii"});

or send the whole Object

Upvotes: 11

Related Questions