Refactor form submission logic in Apply page and BusinessForm component

This commit is contained in:
Pattadon 2024-10-17 15:11:30 +07:00
parent 47baae84fb
commit 7c2b42e116
4 changed files with 93 additions and 38 deletions

View File

@ -13,7 +13,7 @@ import { businessFormSchema } from "@/types/schemas/application.schema";
type businessSchema = z.infer<typeof businessFormSchema>; type businessSchema = z.infer<typeof businessFormSchema>;
export default function Apply() { export default function Apply() {
const [industry, setIndustry] = useState<string[]>([]); const [industry, setIndustry] = useState<{id: number, name: string }[]>([]);
const [projectType, setProjectType] = useState<string[]>([]); const [projectType, setProjectType] = useState<string[]>([]);
const [projectPitch, setProjectPitch] = useState("text"); const [projectPitch, setProjectPitch] = useState("text");
const [applyProject, setApplyProject] = useState(false); const [applyProject, setApplyProject] = useState(false);
@ -22,11 +22,35 @@ export default function Apply() {
const MAX_FILE_SIZE = 5000000; const MAX_FILE_SIZE = 5000000;
const ACCEPTED_IMAGE_TYPES = ["image/jpeg", "image/jpg", "image/png"]; const ACCEPTED_IMAGE_TYPES = ["image/jpeg", "image/jpg", "image/png"];
const onSubmit: SubmitHandler<businessSchema> = async (data) => { const onSubmit: SubmitHandler<businessSchema> = async (data) => {
const transformedData = transformChoice(data); const transformedData = await transformChoice(data);
console.log(transformedData); console.log(transformedData);
await sendRegistration(transformedData);
};
const sendRegistration = async (recvData: any) => {
const {
data: { user },
} = await supabase.auth.getUser();
// console.log(user?.id);
const { data, error } = await supabase
.from("business_application")
.insert([
{
user_id: user?.id,
business_name: recvData["companyName"],
business_type_id: recvData["industry"],
location: recvData["country"],
is_for_sale: recvData["isForSale"],
is_generating_revenue: recvData["isGenerating"],
is_in_us: recvData["isInUS"],
pitch_deck_url: recvData["businessPitchDeck"],
money_raised_to_date: recvData["totalRaised"],
community_size: recvData["communitySize"],
},
])
.select();
console.table(data);
}; };
const createPitchDeckSchema = (inputType: string) => { const createPitchDeckSchema = (inputType: string) => {
@ -289,14 +313,19 @@ export default function Apply() {
const fetchIndustry = async () => { const fetchIndustry = async () => {
let { data: BusinessType, error } = await supabase let { data: BusinessType, error } = await supabase
.from("business_type") .from("business_type")
.select("value"); .select("id, value");
if (error) { if (error) {
console.error(error); console.error(error);
} else { } else {
if (BusinessType) { if (BusinessType) {
// console.table(); // console.table();
setIndustry(BusinessType.map((item) => item.value)); setIndustry(
BusinessType.map((item) => ({
id: item.id,
name: item.value,
}))
);
} }
} }
}; };
@ -375,7 +404,6 @@ export default function Apply() {
setApplyProject={setApplyProject} setApplyProject={setApplyProject}
/> />
{/* </div> {/* </div>
</div> */} </div> */}

View File

@ -18,12 +18,17 @@ import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch"; import { Switch } from "@/components/ui/switch";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@radix-ui/react-tooltip"; import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@radix-ui/react-tooltip";
type businessSchema = z.infer<typeof businessFormSchema>; type businessSchema = z.infer<typeof businessFormSchema>;
interface BusinessFormProps { interface BusinessFormProps {
industry: string[]; industry: {id: number, name:string}[];
applyProject: boolean; applyProject: boolean;
setApplyProject: Function; setApplyProject: Function;
onSubmit: SubmitHandler<businessSchema>; onSubmit: SubmitHandler<businessSchema>;
@ -35,13 +40,13 @@ const BusinessForm = ({
industry, industry,
}: BusinessFormProps & { onSubmit: SubmitHandler<businessSchema> }) => { }: BusinessFormProps & { onSubmit: SubmitHandler<businessSchema> }) => {
const communitySize = [ const communitySize = [
"N/A", { id: 1, name: "N/A" },
"0-5K", { id: 2, name: "0-5K" },
"5-10K", { id: 3, name: "5-10K" },
"10-20K", { id: 4, name: "10-20K" },
"20-50K", { id: 5, name: "20-50K" },
"50-100K", { id: 6, name: "50-100K" },
"100K+", { id: 7, name: "100K+" },
]; ];
const form = useForm<businessSchema>({ const form = useForm<businessSchema>({
resolver: zodResolver(businessFormSchema), resolver: zodResolver(businessFormSchema),
@ -49,14 +54,29 @@ const BusinessForm = ({
}); });
const [businessPitch, setBusinessPitch] = useState("text"); const [businessPitch, setBusinessPitch] = useState("text");
const [businessPitchFile, setBusinessPitchFile] = useState(""); const [businessPitchFile, setBusinessPitchFile] = useState("");
const [countries, setCountries] = useState([]); const [countries, setCountries] = useState<{ id: number; name: string }[]>([]);
useEffect(() => { useEffect(() => {
fetch("https://restcountries.com/v3.1/all") const fetchCountries = async () => {
.then((response) => response.json()) try {
.then((data) => { const response = await fetch("https://restcountries.com/v3.1/all");
const countryList = data.map((country: { name: { common: any; }; }) => country.name.common); if (!response.ok) {
setCountries(countryList.sort()); throw new Error("Network response was not ok");
}); }
const data = await response.json();
const countryList = data.map(
(country: { name: { common: string } }, index: number) => ({
id: index + 1,
name: country.name.common,
})
);
setCountries(countryList.sort((a: { name: string; }, b: { name: any; }) => a.name.localeCompare(b.name)));
} catch (error) {
console.error("Error fetching countries:", error);
}
};
fetchCountries();
}, []); }, []);
return ( return (
<Form {...form}> <Form {...form}>
@ -112,8 +132,9 @@ const BusinessForm = ({
header={<>Country</>} header={<>Country</>}
fieldName="country" fieldName="country"
choices={countries} choices={countries}
handleFunction={(selectedValues: string) => { handleFunction={(selectedValues: any) => {
field.onChange(selectedValues); // console.log("Country selected: " + selectedValues.name);
field.onChange(selectedValues.name);
}} }}
description={ description={
<>Select the country where your business is based.</> <>Select the country where your business is based.</>
@ -138,8 +159,9 @@ const BusinessForm = ({
header={<>Industry</>} header={<>Industry</>}
fieldName="industry" fieldName="industry"
choices={industry} choices={industry}
handleFunction={(selectedValues: string) => { handleFunction={(selectedValues: any) => {
field.onChange(selectedValues); // console.log("Type of selected value:", selectedValues.id);
field.onChange(selectedValues.id);
}} }}
description={ description={
<> <>
@ -389,8 +411,8 @@ const BusinessForm = ({
header={<>What's the rough size of your community?</>} header={<>What's the rough size of your community?</>}
fieldName="communitySize" fieldName="communitySize"
choices={communitySize} choices={communitySize}
handleFunction={(selectedValues: string) => { handleFunction={(selectedValues: any) => {
field.onChange(selectedValues); field.onChange(selectedValues.name);
}} }}
description={ description={
<> <>

View File

@ -8,12 +8,12 @@ import {
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import { ReactElement } from "react"; import { ReactElement, useState } from "react";
interface MultipleOptionSelectorProps { interface MultipleOptionSelectorProps {
header: ReactElement; header: ReactElement;
fieldName: string; fieldName: string;
choices: string[]; choices: { id: number; name: string }[];
handleFunction: Function | null; handleFunction: Function | null;
description: ReactElement; description: ReactElement;
placeholder: string; placeholder: string;
@ -21,6 +21,7 @@ interface MultipleOptionSelectorProps {
} }
export function MultipleOptionSelector(props: MultipleOptionSelectorProps) { export function MultipleOptionSelector(props: MultipleOptionSelectorProps) {
const [value, setValue] = useState("");
return ( return (
<div className="mt-10 space-y-5"> <div className="mt-10 space-y-5">
<Label htmlFor={props.fieldName} className="font-bold text-lg mt-10"> <Label htmlFor={props.fieldName} className="font-bold text-lg mt-10">
@ -28,10 +29,14 @@ export function MultipleOptionSelector(props: MultipleOptionSelectorProps) {
</Label> </Label>
<div className="flex space-x-5"> <div className="flex space-x-5">
<Select <Select
onValueChange={(value) => { value={value}
if (props.handleFunction) { onValueChange={(id) => {
props.handleFunction(props.fieldName, value); setValue(id);
// console.log(value, props.fieldName); const selectedChoice = props.choices.find(
(choice) => choice.id.toString() === id
);
if (selectedChoice && props.handleFunction) {
props.handleFunction(selectedChoice);
} }
}} }}
> >
@ -42,8 +47,8 @@ export function MultipleOptionSelector(props: MultipleOptionSelectorProps) {
<SelectGroup> <SelectGroup>
<SelectLabel>{props.selectLabel}</SelectLabel> <SelectLabel>{props.selectLabel}</SelectLabel>
{props.choices.map((i) => ( {props.choices.map((i) => (
<SelectItem key={i} value={i}> <SelectItem key={i.id} value={i.id.toString()}>
{i} {i.name}
</SelectItem> </SelectItem>
))} ))}
</SelectGroup> </SelectGroup>

View File

@ -95,7 +95,7 @@ const businessFormSchema = z.object({
companyName: z.string().min(5, { companyName: z.string().min(5, {
message: "Company name must be at least 5 characters.", message: "Company name must be at least 5 characters.",
}), }),
industry: z.string({ industry: z.number({
required_error: "Please select one of the option", required_error: "Please select one of the option",
}), }),
isInUS: z isInUS: z