Formik values empty

10,327

You should take a look at the example in formik's docs.

TextField isn't connect to Formik. When the value of TextField changes, Formik don't change, you need Field (import { Field } from 'formik') that will render TextField.

Example for email

<Field
    name="email"
    render={({ field /* _form */ }) => (
        <TextField 
            required
            variant="outlined"
            margin="normal"
            fullWidth
            label="Email"
            autoFocus            
            {...field} 
        />
    )}
/>

If you are using a external input, you should use this way.

Share:
10,327
Admin
Author by

Admin

Updated on June 09, 2022

Comments

  • Admin
    Admin about 2 years

    I have the following Formik form

    <Formik
      initialValues={{
        email: '',
        password: ''
      }}
      onSubmit={(values, { setSubmitting }) => {
        console.log(JSON.stringify(values));
        setSubmitting(true);
        fetch('/login', {
          method: 'POST',
          body: JSON.stringify(values),
          headers: {
            'Content-Type': 'application/json'
          }
        })
          .then(res => res.json())
          .then(response => {
            console.log(response);
            setSubmitting(false);
            if (!response.success) return showAlert();
            login(response.user);
            history.push('/');
          })
          .catch(console.log);
      }}
    >
      {({ isSubmitting }) => (
        <Form className={classes.form}>
          <TextField
            required
            variant="outlined"
            margin="normal"
            fullWidth
            label="Email"
            name="email"
            autoFocus
          />
          <TextField
            required
            variant="outlined"
            margin="normal"
            fullWidth
            name="password"
            label="Wachtwoord"
            type="password"
          />
          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
            disabled={isSubmitting}
          >
            Log in
          </Button>
          <Grid container>
            <Grid item xs>
              <Link href="/register" variant="body2">
                {'Nog geen account? Registreer nu!'}
              </Link>
            </Grid>
          </Grid>
        </Form>
      )}
    </Formik>
    

    For some reason the values in the onSubmit are empty, how can I set it to the values inside the form? The only difference between this form and another one I got to work is that this one does not have a validation schema but I can not imagine that is required