| 1 |
/** |
| 2 |
* Takes a try-catch request exception and sets errors for React Hook Form to consume |
| 3 |
*/ |
| 4 |
import {UseFormSetError} from 'react-hook-form'; |
| 5 |
import {__} from '@wordpress/i18n'; |
| 6 |
|
| 7 |
const generateRequestErrors = (values: Record<string, any>, errors: object[], setError: UseFormSetError<any>) => { |
| 8 |
Object.entries(errors).forEach(([field, value]) => { |
| 9 |
if (Object.keys(values).includes(field)) { |
| 10 |
const fieldElement: HTMLInputElement = document.querySelector('input[name="' + field + '"]'); |
| 11 |
const canFocus = fieldElement && fieldElement.type !== 'hidden'; |
| 12 |
|
| 13 |
setError(field, {message: Array.isArray(value) ? value[0] : value}, {shouldFocus: canFocus}); |
| 14 |
|
| 15 |
if (!canFocus) { |
| 16 |
// In fields that aren't inputs by default or are hidden inputs, we need to use this workaround because the "shouldFocus" option will not work in these cases. |
| 17 |
if (!fieldElement) { |
| 18 |
const fieldElementContainer = document.querySelector('.givewp-fields-' + field); //E.g: <div class="givewp-fields-giftAid">content...</div> |
| 19 |
fieldElementContainer?.scrollIntoView({behavior: 'smooth'}); |
| 20 |
} else { |
| 21 |
fieldElement.parentElement.scrollIntoView({behavior: 'smooth'}); // E.g: <input type="hidden" name="state"> |
| 22 |
} |
| 23 |
} |
| 24 |
} else if (field === 'gateway_error') { |
| 25 |
setError('FORM_ERROR', {message: Array.isArray(value) ? value[0] : value}); |
| 26 |
} else { |
| 27 |
setError('FORM_ERROR', { |
| 28 |
message: __('Something went wrong, please try again or contact support.', 'give'), |
| 29 |
}); |
| 30 |
} |
| 31 |
}); |
| 32 |
}; |
| 33 |
|
| 34 |
export default generateRequestErrors; |
| 35 |
|