Skip to content

Commit ee72305

Browse files
author
ugogo
committed
fix infinite loops, oopsy
1 parent f046163 commit ee72305

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

src/index.tsx

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,13 @@ const ReactInputVerificationCode = ({
2020
length = 4,
2121
onChange,
2222
placeholder = '·',
23-
value: initialValue,
23+
value: pValue,
2424
}: Props) => {
25+
const emptyValue = new Array(length).fill(placeholder);
26+
2527
const [activeIndex, setActiveIndex] = React.useState<number>(-1);
2628
const [value, setValue] = React.useState<string[]>(
27-
initialValue ? initialValue.split('') : new Array(length).fill(placeholder)
29+
pValue ? pValue.split('') : emptyValue
2830
);
2931

3032
const codeInputRef = React.createRef<HTMLInputElement>();
@@ -96,11 +98,13 @@ const ReactInputVerificationCode = ({
9698
setActiveIndex(-1);
9799
};
98100

101+
// handle mobile autocompletion
99102
const onInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
100103
const { value: changeValue } = e.target;
101104
const isCode = isCodeRegex.test(changeValue);
102105

103106
if (!isCode) return;
107+
104108
setValue(changeValue.split(''));
105109
blurItem(activeIndex);
106110
};
@@ -113,6 +117,7 @@ const ReactInputVerificationCode = ({
113117
setActiveIndex(-1);
114118
};
115119

120+
// handle pasting
116121
React.useEffect(() => {
117122
const codeInput = codeInputRef.current;
118123
if (!codeInput) return;
@@ -135,6 +140,19 @@ const ReactInputVerificationCode = ({
135140
onChange(value.join(''));
136141
}, [value]);
137142

143+
React.useEffect(() => {
144+
if (typeof pValue !== 'string') return;
145+
146+
// avoid infinite loop
147+
if (pValue === '' && value.join('') === emptyValue.join('')) return;
148+
149+
// keep internal and external states in sync
150+
if (pValue !== value.join('')) {
151+
console.log('>>> should update');
152+
setValue(pValue.split(''));
153+
}
154+
}, [pValue]);
155+
138156
return (
139157
<React.Fragment>
140158
<Global

0 commit comments

Comments
 (0)