import { create } from 'zustand'; import { RegisterProps } from '../types/auth'; import { registerSchema } from '../validations/auth'; import { ValidationError } from 'yup'; type State = { form: RegisterProps; errors: { [key in keyof RegisterProps]?: string; }; isValid: boolean; isCheckedTNC: boolean; isOpenTNC: boolean; isValidCaptcha: boolean; }; type Action = { updateForm: (name: string, value: string) => void; updateValidCaptcha: (value: boolean) => void; toggleCheckTNC: () => void; openTNC: () => void; closeTNC: () => void; validate: () => void; }; export const useRegisterStore = create((set, get) => ({ form: { company: '', name: '', email: '', password: '', phone: '', }, errors: {}, validate: () => registerSchema .validate(get().form, { abortEarly: false }) .then(() => { set({ errors: {}, isValid: false, }); }) .catch((err: ValidationError) => { const validationErrors: State['errors'] = {}; err.inner.forEach( (e) => (validationErrors[e.path as keyof RegisterProps] = e.message) ); set({ errors: validationErrors, isValid: false, }); }), isValid: false, isCheckedTNC: false, isOpenTNC: false, isValidCaptcha: false, updateForm: (name, value) => set((state) => { const updatedForm = { ...state.form, [name]: value }; const fieldKeys = Object.keys( updatedForm ) as (keyof typeof updatedForm)[]; const allFieldsValid = fieldKeys.every((key) => { const value = updatedForm[key]; if (key === 'company') return true; return value !== ''; }); return { form: updatedForm, isValid: allFieldsValid, }; }), toggleCheckTNC: () => set((state) => ({ isCheckedTNC: !state.isCheckedTNC })), openTNC: () => set(() => ({ isOpenTNC: true })), closeTNC: () => set(() => ({ isOpenTNC: false })), updateValidCaptcha: (value) => set(() => ({ isValidCaptcha: value })), }));