Просмотр исходного кода

fix: optimize onComplete/onIncomplete invocation (#32)

Ensure onComplete is invoked only once when the
pin input is fully completed. Invoke onIncomplete
only once when the pin input changes from complete
to incomplete.
Sat Naing 1 год назад
Родитель
Сommit
3718cc4e2d
1 измененных файлов с 11 добавлено и 7 удалено
  1. 11 7
      src/components/custom/pin-input.tsx

+ 11 - 7
src/components/custom/pin-input.tsx

@@ -111,18 +111,22 @@ const PinInput = React.forwardRef<HTMLDivElement, PinInputProps>(
 
     /* call onChange func if pinValue changes */
     React.useEffect(() => {
-      onChange && onChange(pinValue)
+      if (!onChange) return
+      onChange(pinValue)
     }, [onChange, pinValue])
 
-    /* call onComplete func if pinValue is valid and completed */
+    /* call onComplete/onIncomplete func if pinValue is valid and completed/incompleted */
+    const completeRef = React.useRef(pinValue.length === length)
     React.useEffect(() => {
-      if (onComplete && pinValue.length === length) {
-        onComplete(pinValue)
+      if (pinValue.length === length && completeRef.current === false) {
+        completeRef.current = true
+        if (onComplete) onComplete(pinValue)
       }
-      if (onIncomplete && pinValue.length !== length) {
-        onIncomplete(pinValue)
+      if (pinValue.length !== length && completeRef.current === true) {
+        completeRef.current = false
+        if (onIncomplete) onIncomplete(pinValue)
       }
-    }, [length, onComplete, onIncomplete, pinValue])
+    }, [length, onComplete, onIncomplete, pinValue, pins, value])
 
     /* focus on first input field if autoFocus is set */
     React.useEffect(() => {