import React from 'react';
2 import { useFormikContext, Formik, Form, Field } from 'formik';
3
4 const AutoSubmitToken = () => {
5
6 const { values, submitForm } = useFormikContext();
7 React.useEffect(() => {
8
9 if (values.token.length === 6) {
10 submitForm();
11 }
12 }, [values, submitForm]);
13 return null;
14 };
15
16 const TwoFactorVerificationForm = () => (
17 <div>
18 <h1>2-step Verification</h1>
19 <p>Please enter the 6 digit code sent to your device</p>
20 <Formik
21 initialValues={{ token: '' }}
22 validate={values => {
23 const errors = {};
24 if (values.token.length < 5) {
25 errors.token = 'Invalid code. Too short.';
26 }
27 return errors;
28 }}
29 onSubmit={(values, actions) => {
30 setTimeout(() => {
31 alert(JSON.stringify(values, null, 2));
32 actions.setSubmitting(false);
33 }, 1000);
34 }}
35 >
36 <Form>
37 <Field name="token" type="tel" />
38 <AutoSubmitToken />
39 </Form>
40 </Formik>
41 </div>
42 );