frontPanel/src/stores/contactForm.ts

78 lines
2.4 KiB
TypeScript
Raw Normal View History

import { create } from "zustand";
import { sendContactFormRequest } from "../api/contactForm";
import { getMessageFromFetchError } from "../utils/backendMessageHandler";
interface ContactFormStore {
isModalOpen: boolean;
isSubmitDisabled: boolean;
mail: string;
phoneNumberField: string;
telegramField: string;
whatsappField: string;
}
const initialState: ContactFormStore = {
isModalOpen: false,
isSubmitDisabled: false,
mail: "",
phoneNumberField: "",
telegramField: "",
whatsappField: "",
};
export const useContactFormStore = create<ContactFormStore>()(
2023-12-31 02:53:25 +00:00
(set, get) => initialState,
);
2023-12-31 02:53:25 +00:00
export const setIsContactFormOpen = (
isModalOpen: ContactFormStore["isModalOpen"],
) => useContactFormStore.setState({ isModalOpen });
export const setContactFormMailField = (mail: ContactFormStore["mail"]) =>
useContactFormStore.setState({ mail });
export const setContactFormTelegramField = (
telegramField: ContactFormStore["telegramField"],
) => useContactFormStore.setState({ telegramField });
export const setIsSubmitDisabled = (
isSubmitDisabled: ContactFormStore["isSubmitDisabled"],
) => useContactFormStore.setState({ isSubmitDisabled });
export const setContactFormPhoneNumberField = (
phoneNumberField: ContactFormStore["phoneNumberField"],
) => {
if (/^\+?\d*$/.test(phoneNumberField))
useContactFormStore.setState({ phoneNumberField });
};
2023-12-31 02:53:25 +00:00
export const setContactFormWhatsappField = (
whatsappField: ContactFormStore["whatsappField"],
) => {
if (/^\+?\d*$/.test(whatsappField))
useContactFormStore.setState({ whatsappField });
};
export const sendContactForm = async (): Promise<string | null> => {
2023-12-31 02:53:25 +00:00
const { mail, phoneNumberField, telegramField, whatsappField } =
useContactFormStore.getState();
if (!mail) return "Почта не указана";
if (!mail.includes("@")) return "Почта некорректна";
let contact = "Опросник, предрегистрация";
try {
useContactFormStore.setState({ isSubmitDisabled: true });
2024-05-13 13:24:41 +00:00
const [_, error, status] = await sendContactFormRequest({
contact,
whoami: mail,
});
2024-05-13 13:24:41 +00:00
if (status !== 200) {
throw new Error(error);
}
useContactFormStore.setState({ ...initialState });
2023-12-31 02:53:25 +00:00
return "Данные отправлены";
} catch (error: any) {
useContactFormStore.setState({ isSubmitDisabled: false });
return getMessageFromFetchError(error);
}
};