refactored code

This commit is contained in:
2026-05-25 11:32:45 +02:00
parent 636730d4b2
commit f7a0a3753c
2 changed files with 37 additions and 25 deletions
+11 -25
View File
@@ -27,37 +27,15 @@ import { SelectUserModal } from "../components/modals/SelectUserModal";
import { useForm } from "@tanstack/react-form";
import { changeTranslation } from "../utils/uxFncs";
import { createFormSchema } from "../config/interfaces.config";
import type { ZodObject, ZodRawShape } from "zod";
import { validateFieldWithZod } from "../utils/uxFncs";
import { TextField } from "../components/TextField";
const PAYMENT_METHODS = ["bar", "paypal", "andere"] as const;
const PAYMENT_LABELS: Record<string, string> = {
bar: "Cash",
paypal: "PayPal",
andere: "Transfer",
};
/**
* Validates a single field against the full Zod schema.
* Returns the first error message for that field, or undefined if valid.
*/
function validateFieldWithZod(
schema: ZodObject<ZodRawShape>,
fieldName: string,
allValues: Record<string, unknown>,
): string | undefined {
const result = schema.safeParse(allValues);
if (result.success) return undefined;
const issue = result.error.issues.find(
(i) => i.path.length === 1 && i.path[0] === fieldName,
);
return issue?.message;
}
import { PAYMENT_METHODS, PAYMENT_LABELS } from "../utils/uxFncs";
export const MainForm = () => {
const { t } = useTranslation();
const queryClient = useQueryClient();
// States
const [invoice, setInvoice] = useState(false);
const [msg, setMsg] = useState<Message | null>(null);
const [selectedUser, setSelectedUser] = useState<string | null>(null);
@@ -66,6 +44,7 @@ export const MainForm = () => {
const formSchema = createFormSchema(t, invoice);
// Validates the fields and makes sure that the form is maching the zod schema
const makeFieldValidator = (fieldName: string) => ({
onSubmit: ({
fieldApi,
@@ -85,6 +64,7 @@ export const MainForm = () => {
},
});
// Creates a form with tanstack form
const { Field, Subscribe, handleSubmit, setFieldValue } = useForm({
defaultValues: {
firstName: "",
@@ -108,6 +88,7 @@ export const MainForm = () => {
},
});
// This function returns the errors for one field
const getErrors = (field: {
state: { meta: { errorMap: Record<string, unknown> } };
}) => {
@@ -122,6 +103,7 @@ export const MainForm = () => {
return [...blurErrors, ...submitErrors].filter(Boolean);
};
// useEffect that only executes on mount and is checking if there is a user selcted in the cookies
useEffect(() => {
const savedUser = Cookies.get("selectedUser");
if (savedUser) {
@@ -135,17 +117,20 @@ export const MainForm = () => {
}
}, []);
// Fetch users tanstack query
const { data: usernameData, isLoading: usernameDataIsLoading } = useQuery({
queryKey: ["users"],
queryFn: fetchUsers,
});
// Query for validating selcted user
const { data: userData } = useQuery({
queryKey: ["user", selectedUser],
enabled: !!selectedUser,
queryFn: () => confirmUser(selectedUser),
});
// Tanstack query (mutate) for sending the form
const { mutate: mutateForm, isPending: mutateFormIsPending } = useMutation({
mutationFn: (values: FormData) => submitFormData(values, selectedUser),
onSuccess: (_, values) => {
@@ -164,6 +149,7 @@ export const MainForm = () => {
const nextID = userData?.nextID ?? "N/A";
// function for selecting user
const handleUserSelection = (username: string | null) => {
if (username == null || username == "") {
return;
+26
View File
@@ -1,5 +1,7 @@
import i18n from "./i18n";
import Cookies from "js-cookie";
import { ZodObject } from "zod";
import type { ZodRawShape } from "zod";
export const changeTranslation = () => {
const clientLng = i18n.language;
@@ -14,3 +16,27 @@ export const changeTranslation = () => {
alert("Cannot change language.");
}
};
/**
* Validates a single field against the full Zod schema.
* Returns the first error message for that field, or undefined if valid.
*/
export function validateFieldWithZod(
schema: ZodObject<ZodRawShape>,
fieldName: string,
allValues: Record<string, unknown>,
): string | undefined {
const result = schema.safeParse(allValues);
if (result.success) return undefined;
const issue = result.error.issues.find(
(i) => i.path.length === 1 && i.path[0] === fieldName,
);
return issue?.message;
}
export const PAYMENT_METHODS = ["bar", "paypal", "andere"] as const;
export const PAYMENT_LABELS: Record<string, string> = {
bar: "Cash",
paypal: "PayPal",
andere: "Transfer",
};