CreateSubRegionForm logic unfinished
All checks were successful
Vercel Preview Deployment / Deploy-Preview (push) Successful in 1m16s

This commit is contained in:
ChrQR 2024-06-03 15:28:22 +02:00
parent 4b554cdb37
commit 7304ce1023
8 changed files with 172 additions and 7 deletions

View File

@ -4,6 +4,8 @@ import CreateCountry from "./_components/admin/CreateCountry";
import AllCountries from "./_components/AllCountries";
import CreateRegion from "./_components/admin/CreateRegion";
import AllRegions from "./_components/AllRegions";
import CreateSubRegionForm from "./_components/admin/CreateSubRegionForm";
import CreateSubRegion from "./_components/admin/CreateSubRegion";
export default function App() {
return (
@ -14,6 +16,7 @@ export default function App() {
<AllCountries />
<CreateRegion />
<AllRegions />
<CreateSubRegion />
</div>
);
}

View File

@ -2,9 +2,9 @@ import CreateCountryForm from "./CreateCountryForm";
export default function CreateCountry() {
return (
<>
<div className="container flex w-full flex-col justify-center py-4">
<h1 className="pt-4 text-2xl">Fill the form to create a new country</h1>
<CreateCountryForm />
</>
</div>
);
}

View File

@ -1,13 +1,14 @@
"use server";
import { db } from "~/server/db";
import CreateRegionForm from "./CreateRegionForm";
import getAllCountries from "~/server/actions/getAllCountries";
export default async function CreateRegion() {
const allCountries = await db.query.countries.findMany();
const allCountries = await getAllCountries();
return (
<>
<div className="container flex w-full flex-col justify-center py-4">
<h1 className="pt-4 text-2xl">Fill the form to create a new region</h1>
<CreateRegionForm countries={allCountries} />
</>
</div>
);
}

View File

@ -0,0 +1,18 @@
"use server";
import getAllRegions from "~/server/actions/getAllRegions";
import CreateSubRegionForm from "./CreateSubRegionForm";
import getAllCountries from "~/server/actions/getAllCountries";
const allRegions = await getAllRegions();
const allCountries = await getAllCountries();
export default async function CreateSubRegion() {
return (
<div className="container flex w-full flex-col justify-center py-4">
<h1 className="pt-4 text-2xl">
Fill the form to create a new Sub Region
</h1>
<CreateSubRegionForm regions={allRegions} countries={allCountries} />
</div>
);
}

View File

@ -0,0 +1,81 @@
"use client";
import clsx from "clsx";
import { useState } from "react";
import { useFormState } from "react-dom";
import { Input } from "~/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "~/components/ui/select";
import { addRegion } from "~/server/actions/addRegion";
type Region = {
id: string;
name: string;
countryId: string;
};
type Country = {
id: string;
name: string;
};
export default function CreateSubRegionForm(props: {
regions: Region[];
countries: Country[];
}) {
const { countries, regions } = props;
const [country, setCountry] = useState<Country | undefined>(undefined);
const [formState, formActions] = useFormState(addRegion, {
message: "",
errors: undefined,
fieldValues: {
name: "",
regionId: "",
},
});
return (
<div>
{/* country selector */}
<Select name="country">
<SelectTrigger
className={`w-[180px] ${clsx({ "border-red-500": formState.errors?.countryId })}`}
>
<SelectValue placeholder="Country" />
</SelectTrigger>
<SelectContent>
{countries.map((country) => (
<SelectItem key={country.id} value={country.id}>
{country.name}
</SelectItem>
))}
</SelectContent>
</Select>
<form action={formActions}>
{/* region selector */}
<Select name="subRegion">
<SelectTrigger
className={`w-[180px] ${clsx({ "border-red-500": formState.errors?.countryId })}`}
>
<SelectValue placeholder="Region" />
</SelectTrigger>
<SelectContent>
{regions.map((region) => (
<SelectItem key={region.id} value={region.id}>
{region.name}
</SelectItem>
))}
</SelectContent>
</Select>
<Input
name="name"
id="name"
placeholder="Name"
className={`${clsx({ "border-red-500": formState.errors?.name })}`}
/>
</form>
</div>
);
}

View File

@ -20,7 +20,7 @@ export async function addCountry(prevstate: any, formData: FormData) {
name: z
.string()
.min(1, { message: "Name is required" })
.refine(() => !exists[0], { message: `${name} already exists` }),
.refine(() => !exists, { message: `${name} already exists` }),
});
//Parse the form data using the schema for validation, and check if the name already exists
try {

View File

@ -23,7 +23,7 @@ export const addRegion = async (prevstate: any, formData: FormData) => {
name: z
.string()
.min(1, "Name is required")
.refine(() => !exists[0], {
.refine(() => !exists, {
message: `${name} already exists in selected country`,
}),
});

View File

@ -0,0 +1,62 @@
"use server";
import { eq } from "drizzle-orm";
import { db } from "../db";
import { subRegions } from "../db/schema";
import { ZodError, z } from "zod";
export const addSubRegion = async (prevstate: any, formData: FormData) => {
//assign formdaata to variables.
const name = (formData.get("name") as string).toLowerCase();
const regionId = formData.get("region") as string;
//check if region already exists in country
const exists = await db
.select({ name: subRegions.name })
.from(subRegions)
.where(eq(subRegions.regionId, regionId) && eq(subRegions.name, name));
//Define the schema for the form data
const schema = z.object({
regionId: z.string().min(1, "No region selected"),
name: z
.string()
.min(1, "Name is required")
.refine(() => !exists, {
message: `${name} already exists in selected region`,
}),
});
//Parse the form data using the schema for validation, and check if the name already exists
try {
schema.parse({
regionId,
name,
});
//If the name doesn't exist, add the country to the database abd revalidate the page
await db.insert(subRegions).values({ regionId, name });
//Return a success message
return {
message: "success",
errors: undefined,
fieldValues: {
name: "",
regionId: "",
},
};
} catch (error) {
const zodError = error as ZodError;
const errorMap = zodError.flatten().fieldErrors;
//Return an error object with the field values and errors.
return {
message: "error",
errors: {
name: errorMap["name"]?.[0] ?? "",
regionId: errorMap["regionId"]?.[0] ?? "",
},
fieldValues: {
name,
regionId,
},
};
}
};