Skip to content

Commit

Permalink
Merge pull request #23995 from samh-nl/fix/issue-21958
Browse files Browse the repository at this point in the history
fix: revalidate upon input and refocus if error occurs
  • Loading branch information
amyevans authored Aug 14, 2023
2 parents 7e5c8f5 + 3d8bad4 commit 6d1b992
Showing 1 changed file with 24 additions and 5 deletions.
29 changes: 24 additions & 5 deletions src/components/MagicCodeInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,21 +114,35 @@ function MagicCodeInput(props) {
},
}));

const validateAndSubmit = () => {
const numbers = decomposeString(props.value, props.maxLength);
/**
* Validate the entered code and submit
*
* @param {String} value
*/
const validateAndSubmit = (value) => {
const numbers = decomposeString(value, props.maxLength);
if (!props.shouldSubmitOnComplete || _.filter(numbers, (n) => ValidationUtils.isNumeric(n)).length !== props.maxLength || props.network.isOffline) {
return;
}
// Blurs the input and removes focus from the last input and, if it should submit
// on complete, it will call the onFulfill callback.
blurMagicCodeInput();
props.onFulfill(props.value);
props.onFulfill(value);
};

useNetwork({onReconnect: validateAndSubmit});
useNetwork({onReconnect: () => validateAndSubmit(props.value)});

useEffect(() => {
validateAndSubmit();
if (!props.hasError) {
return;
}

// Focus the last input if an error occurred to allow for corrections
inputRefs.current[props.maxLength - 1].focus();
}, [props.hasError, props.maxLength]);

useEffect(() => {
validateAndSubmit(props.value);

// We have not added:
// + the editIndex as the dependency because we don't want to run this logic after focusing on an input to edit it after the user has completed the code.
Expand Down Expand Up @@ -179,6 +193,11 @@ function MagicCodeInput(props) {

const finalInput = composeToString(numbers);
props.onChangeText(finalInput);

// If the same number is pressed, we cannot depend on props.value in useEffect for re-submitting
if (props.value === finalInput) {
validateAndSubmit(finalInput);
}
};

/**
Expand Down

0 comments on commit 6d1b992

Please sign in to comment.