Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions src/components/MagicCodeInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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);
}
};

/**
Expand Down