Skip to content

Commit

Permalink
fix: optimize onComplete/onIncomplete invocation (#32)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
satnaing authored Sep 22, 2024
1 parent bc75eab commit 3718cc4
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions src/components/custom/pin-input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand Down

0 comments on commit 3718cc4

Please sign in to comment.