2019-11-06 15:21:58 +00:00
|
|
|
import { AddressTypeInput } from "@saleor/customers/types";
|
2020-07-07 10:14:12 +00:00
|
|
|
import { AccountErrorFragment } from "@saleor/fragments/types/AccountErrorFragment";
|
2021-05-06 11:38:15 +00:00
|
|
|
import { transformFormToAddressInput } from "@saleor/misc";
|
|
|
|
import {
|
|
|
|
AccountErrorCode,
|
|
|
|
AddressInput,
|
|
|
|
AddressTypeEnum
|
|
|
|
} from "@saleor/types/globalTypes";
|
2019-11-06 15:21:58 +00:00
|
|
|
import { add, remove } from "@saleor/utils/lists";
|
2020-05-14 09:30:32 +00:00
|
|
|
import { useState } from "react";
|
2019-11-06 15:21:58 +00:00
|
|
|
|
2020-10-22 11:33:29 +00:00
|
|
|
interface UseAddressValidation<TInput, TOutput> {
|
2020-03-11 09:55:14 +00:00
|
|
|
errors: AccountErrorFragment[];
|
2020-10-22 11:33:29 +00:00
|
|
|
submit: (data: TInput & AddressTypeInput) => TOutput;
|
2019-11-06 15:21:58 +00:00
|
|
|
}
|
|
|
|
|
2020-10-22 11:33:29 +00:00
|
|
|
function useAddressValidation<TInput, TOutput>(
|
2021-05-06 11:38:15 +00:00
|
|
|
onSubmit: (address: TInput & AddressInput) => TOutput,
|
|
|
|
addressType?: AddressTypeEnum
|
2020-10-22 11:33:29 +00:00
|
|
|
): UseAddressValidation<TInput, TOutput> {
|
2020-03-11 09:55:14 +00:00
|
|
|
const [validationErrors, setValidationErrors] = useState<
|
|
|
|
AccountErrorFragment[]
|
|
|
|
>([]);
|
2019-11-06 15:21:58 +00:00
|
|
|
|
2020-03-11 09:55:14 +00:00
|
|
|
const countryRequiredError: AccountErrorFragment = {
|
|
|
|
__typename: "AccountError",
|
|
|
|
code: AccountErrorCode.REQUIRED,
|
2021-05-06 11:38:15 +00:00
|
|
|
field: "country",
|
|
|
|
addressType
|
2019-11-06 15:21:58 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
return {
|
|
|
|
errors: validationErrors,
|
2020-10-22 11:33:29 +00:00
|
|
|
submit: (data: TInput & AddressTypeInput) => {
|
2019-11-06 15:21:58 +00:00
|
|
|
try {
|
|
|
|
setValidationErrors(
|
|
|
|
remove(
|
|
|
|
countryRequiredError,
|
|
|
|
validationErrors,
|
|
|
|
(a, b) => a.field === b.field
|
|
|
|
)
|
|
|
|
);
|
2021-05-06 11:38:15 +00:00
|
|
|
return onSubmit(transformFormToAddressInput(data));
|
2019-11-06 15:21:58 +00:00
|
|
|
} catch {
|
|
|
|
setValidationErrors(add(countryRequiredError, validationErrors));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export default useAddressValidation;
|