2019-11-06 15:21:58 +00:00
|
|
|
import { useState } from "react";
|
|
|
|
import { useIntl } from "react-intl";
|
|
|
|
|
|
|
|
import { AddressTypeInput } from "@saleor/customers/types";
|
|
|
|
import { commonMessages } from "@saleor/intl";
|
|
|
|
import { transformFormToAddress } from "@saleor/misc";
|
|
|
|
import { UserError } from "@saleor/types";
|
|
|
|
import { AddressInput } from "@saleor/types/globalTypes";
|
|
|
|
import { add, remove } from "@saleor/utils/lists";
|
|
|
|
|
2019-11-13 13:50:38 +00:00
|
|
|
interface UseAddressValidation<T> {
|
2019-11-06 15:21:58 +00:00
|
|
|
errors: UserError[];
|
2019-11-13 13:50:38 +00:00
|
|
|
submit: (data: T & AddressTypeInput) => void;
|
2019-11-06 15:21:58 +00:00
|
|
|
}
|
|
|
|
|
2019-11-13 13:50:38 +00:00
|
|
|
function useAddressValidation<T>(
|
|
|
|
onSubmit: (address: T & AddressInput) => void
|
|
|
|
): UseAddressValidation<T> {
|
2019-11-06 15:21:58 +00:00
|
|
|
const intl = useIntl();
|
|
|
|
const [validationErrors, setValidationErrors] = useState<UserError[]>([]);
|
|
|
|
|
|
|
|
const countryRequiredError = {
|
|
|
|
field: "country",
|
|
|
|
message: intl.formatMessage(commonMessages.requiredField)
|
|
|
|
};
|
|
|
|
|
|
|
|
return {
|
|
|
|
errors: validationErrors,
|
2019-11-13 13:50:38 +00:00
|
|
|
submit: (data: T & AddressTypeInput) => {
|
2019-11-06 15:21:58 +00:00
|
|
|
try {
|
|
|
|
setValidationErrors(
|
|
|
|
remove(
|
|
|
|
countryRequiredError,
|
|
|
|
validationErrors,
|
|
|
|
(a, b) => a.field === b.field
|
|
|
|
)
|
|
|
|
);
|
|
|
|
onSubmit(transformFormToAddress(data));
|
|
|
|
} catch {
|
|
|
|
setValidationErrors(add(countryRequiredError, validationErrors));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export default useAddressValidation;
|