From 9669fe14d77e11227df3635af584347cf086915b Mon Sep 17 00:00:00 2001 From: Mirlan Date: Thu, 9 Jul 2020 16:30:36 +0600 Subject: [PATCH] Ott 212 zipcode validation (#31) --- .../components/RegistrationStep/index.tsx | 2 - src/hooks/useRequest.tsx | 78 +++++++++++++++++++ 2 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 src/hooks/useRequest.tsx diff --git a/src/features/Register/components/RegistrationStep/index.tsx b/src/features/Register/components/RegistrationStep/index.tsx index a056cf43..4d9e63d7 100644 --- a/src/features/Register/components/RegistrationStep/index.tsx +++ b/src/features/Register/components/RegistrationStep/index.tsx @@ -16,7 +16,6 @@ import { emailRegex } from '../../helpers/isValidEmail' import { useForm } from './hooks/useForm' const commonFieldRegex = '^.{0,500}$' -const postalCodeRegex = '^\\d{5}(?:[-\\s]\\d{4})?$' const labelWidth = 116 export const RegistrationStep = () => { @@ -111,7 +110,6 @@ export const RegistrationStep = () => { id={formIds.postalCode} labelLexic='form_postal_code' labelWidth={labelWidth} - pattern={postalCodeRegex} title={defaultMessage} /> { + const [isFetching, setFetchingState] = useState(false) + const [error, setError] = useState(null) + + const switchState = useCallback( + (promise: Promise) => { + setFetchingState(true) + setError(null) + return promise + .catch((err) => { + setError(err) + return Promise.reject(err) + }) + .finally(() => setFetchingState(false)) + }, + [], + ) + + return { + error, + isFetching, + switchState, + } +} + +/** + * Хук для состояния загрузки. + * Получает asyncFunction функция возвращающая Promise + * и возвращает функцию обертку над asyncFunction + * + * Загрузка начинается при вызове обертки, заканчивается при завершении Promise + * + * ```ts + * const [countries, setCountries] = useState([]) + * + * const { request: fetchCountries, isFetching } = useRequest(getCountries) + * + * useEffect(() => { + * fetchCountries().then(setCountries) + * }, []) + * + * return ( + *
+ * {isFetching && 'Loading...'} + * ... + *
+ * ) + * ``` + */ +export const useRequest = < + F extends (...args: any) => Promise, +>(asyncFunction: F) => { + const { + error, + isFetching, + switchState, + } = useRequestState() + + const request = useCallback( + (...args: Parameters) => ( + switchState(asyncFunction(...args)) as ReturnType + ), + [switchState, asyncFunction], + ) + + return { + error, + isFetching, + request, + } +}