Преглед изворни кода

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, {
         return React.cloneElement(child, {
           name,
           name,
           inputKey: `input-${pinIndex}`,
           inputKey: `input-${pinIndex}`,
-          defaultValue: length > pinIndex ? pins[pinIndex] : '',
+          value: length > pinIndex ? pins[pinIndex] : '',
           onChange: (e: React.ChangeEvent<HTMLInputElement>) =>
           onChange: (e: React.ChangeEvent<HTMLInputElement>) =>
             handlers.handleChange(e, pinIndex),
             handlers.handleChange(e, pinIndex),
           onFocus: (e: React.FocusEvent<HTMLInputElement>) =>
           onFocus: (e: React.FocusEvent<HTMLInputElement>) =>
@@ -266,12 +266,30 @@ const usePinInput = ({
   length,
   length,
   readOnly,
   readOnly,
 }: UsePinInputProps) => {
 }: 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 [pins, setPins] = React.useState<(string | number)[]>(pinInputs)
   const pinValue = pins.join('').trim()
   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)
   const itemsRef = React.useRef<Map<number, HTMLInputElement> | null>(null)
 
 
   function getMap() {
   function getMap() {