diff --git a/src/components/admin/resources/form.tsx b/src/components/admin/resources/form.tsx index f55e15d..488c3e4 100644 --- a/src/components/admin/resources/form.tsx +++ b/src/components/admin/resources/form.tsx @@ -25,7 +25,7 @@ import { } from "../../forms/selectors"; import { GenericInput, InfoInputLine } from "~/components/forms/textInput"; import { PriceIcon } from "~/prices/Icons"; -import { type Dispatch, type SetStateAction, useState } from "react"; +import { type Dispatch, type SetStateAction, useState, useEffect } from "react"; import { type UseFormReturn, FormProvider, @@ -82,7 +82,8 @@ const LinkModal = ({ isOpen: boolean; setOpen: Dispatch>; }) => { - const { register } = useForm(); + const { setValue, getValues } = useFormContext(); + const { register, handleSubmit } = useForm(); const platformTypeOptions = [ { label: "Website", @@ -102,6 +103,14 @@ const LinkModal = ({ }, ]; + const onSubmit = (data: PlatformLink) => { + const values = getValues().platform_links ?? []; + + values.push(data); + setValue("platform_links", values); + setOpen(false); + }; + return ( -
+
{ + handleSubmit(onSubmit)(event).catch((error) => { + console.error(error); + }); + }} + className="space-y-4 p-4" + > -
+
+ +
+
); @@ -165,10 +189,30 @@ const LinkModal = ({ * Contains the input fields for editing the links for a resource * @returns */ -const ResourceLinkSubForm = ({ links }: { links: PlatformLink[] }) => { - const { register } = useFormContext(); +const ResourceLinkSubForm = () => { + const { setValue, getValues, watch } = useFormContext(); const [linkModalOpen, setLinkModalOpen] = useState(false); - const [selectedLinks, setSelectedLinks] = useState(links); + const [selectedLinks, setSelectedLinks] = useState( + getValues().platform_links ?? [] + ); + + useEffect(() => { + watch((value, { name }) => { + if (name === "platform_links") { + const validLinks = value.platform_links?.filter((value) => { + return value?.link && value?.platform; + }) as unknown as PlatformLink[]; + setSelectedLinks(validLinks); + } + }); + }, [watch]); + + const removeLink = (key: number) => { + const newLinks = [...selectedLinks]; + newLinks.splice(key, 1); + + setValue("platform_links", newLinks); + }; return (
@@ -197,6 +241,9 @@ const ResourceLinkSubForm = ({ links }: { links: PlatformLink[] }) => {