saleor-dashboard/src/hooks/useAddressValidation.ts

46 lines
1.4 KiB
TypeScript
Raw Normal View History

2019-11-06 15:21:58 +00:00
import { AddressTypeInput } from "@saleor/customers/types";
import { AccountErrorFragment } from "@saleor/fragments/types/AccountErrorFragment";
2019-11-06 15:21:58 +00:00
import { transformFormToAddress } from "@saleor/misc";
import { AccountErrorCode, AddressInput } from "@saleor/types/globalTypes";
2019-11-06 15:21:58 +00:00
import { add, remove } from "@saleor/utils/lists";
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>(
onSubmit: (address: TInput & AddressInput) => TOutput
): 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,
field: "country"
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
)
);
2020-10-22 11:33:29 +00:00
return onSubmit(transformFormToAddress(data));
2019-11-06 15:21:58 +00:00
} catch {
setValidationErrors(add(countryRequiredError, validationErrors));
}
}
};
}
export default useAddressValidation;