简体   繁体   中英

Formik values empty

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

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.

You need to pass this

onChangeText={handleChange('email')}
onBlur={handleBlur('email')}
value={values.email}

to the Textinput , and for Password aswell. Your Textinput doesn't track any changes or submission.

Check here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM