소스 검색

fix: sync pin inputs programmatically

Updated pin input for the synchronization.
Before this, when the pin input value is updated
programmatically, pin inputs are not updated properly
i.e,. not sync properly. This commit fixes that issue
by using useEffect and useMemo.
satnaing 2 년 전
부모
커밋
f477f3ac05
1개의 변경된 파일21개의 추가작업 그리고 3개의 파일을 삭제
  1. 21 3
      src/components/custom/pin-input.tsx

+ 21 - 3
src/components/custom/pin-input.tsx

@@ -142,7 +142,7 @@ const PinInput = React.forwardRef<HTMLDivElement, PinInputProps>(
         return React.cloneElement(child, {
           name,
           inputKey: `input-${pinIndex}`,
-          defaultValue: length > pinIndex ? pins[pinIndex] : '',
+          value: length > pinIndex ? pins[pinIndex] : '',
           onChange: (e: React.ChangeEvent<HTMLInputElement>) =>
             handlers.handleChange(e, pinIndex),
           onFocus: (e: React.FocusEvent<HTMLInputElement>) =>
@@ -266,12 +266,30 @@ const usePinInput = ({
   length,
   readOnly,
 }: UsePinInputProps) => {
-  const pinInputs = Array.from({ length }, (_, index) =>
-    defaultValue ? defaultValue.charAt(index) : value ? value.charAt(index) : ''
+  const pinInputs = React.useMemo(
+    () =>
+      Array.from({ length }, (_, index) =>
+        defaultValue
+          ? defaultValue.charAt(index)
+          : value
+            ? value.charAt(index)
+            : ''
+      ),
+    [defaultValue, length, value]
   )
+
   const [pins, setPins] = React.useState<(string | number)[]>(pinInputs)
   const pinValue = pins.join('').trim()
 
+  /**
+   * Update pins when values changes.
+   * This is necessary and this allows pins to be synced
+   * when the value is update or reset programmatically
+   */
+  React.useEffect(() => {
+    setPins(pinInputs)
+  }, [pinInputs])
+
   const itemsRef = React.useRef<Map<number, HTMLInputElement> | null>(null)
 
   function getMap() {