diff --git a/src/components/MagicCodeInput.js b/src/components/MagicCodeInput.js index cea98cfd3747..0bb1b76ceeff 100644 --- a/src/components/MagicCodeInput.js +++ b/src/components/MagicCodeInput.js @@ -119,21 +119,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. @@ -206,6 +220,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); + } }; /**