Skip to content

Commit b96a683

Browse files
authored
field-otp: improve autoSubmit (#128)
1 parent bdb6691 commit b96a683

1 file changed

Lines changed: 22 additions & 4 deletions

File tree

β€Žsrc/components/form/field-otp.tsxβ€Ž

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
import { useStore } from '@tanstack/react-form';
2-
import { ComponentProps, ComponentRef, useRef } from 'react';
2+
import {
3+
ComponentProps,
4+
ComponentRef,
5+
useCallback,
6+
useEffect,
7+
useRef,
8+
} from 'react';
39
import { Box, BoxProps, PinInput } from 'react-native-ficus-ui';
410

511
import { FormFieldError } from '@/lib/tanstack-form/components';
@@ -28,6 +34,21 @@ export default function FieldOtp(
2834
};
2935
});
3036

37+
const shouldAutoSubmit =
38+
autoSubmit && field.state.value?.length === codeLength;
39+
40+
const submitForm = useCallback(() => {
41+
if (!field.form.state.isSubmitted) {
42+
field.form.handleSubmit();
43+
}
44+
}, [field.form]);
45+
46+
useEffect(() => {
47+
if (shouldAutoSubmit) {
48+
submitForm();
49+
}
50+
}, [shouldAutoSubmit, submitForm]);
51+
3152
return (
3253
<Box {...containerProps} ref={containerRef}>
3354
<PinInput
@@ -45,9 +66,6 @@ export default function FieldOtp(
4566
value={field.state.value}
4667
onChangeText={(value) => {
4768
field.handleChange(value);
48-
if (autoSubmit && value.length === codeLength) {
49-
field.form.handleSubmit();
50-
}
5169
}}
5270
onBlur={(e) => {
5371
field.handleBlur();

0 commit comments

Comments
Β (0)