admin管理员组文章数量:1344321
Why I can't delete the data if its left alone? I'm having a hard time how can I debug this, I'm using react-hook-form and maximizing the use of useFieldArray
. I already have the ability to add and update, but the main problem is deleting.
I will send an image an for example first, its giving me a headache.
This first image, I have two resource, one is research gate and google, now I will delete the google first.
It got deleted, I will update author details and I open it again.
Now this time, I re-open it, and now what I'm going to do is delete the resarch gate
It got deleted right, but I will click update author again, then open it again.
It still here.
UpdateAuthor.tsx
const UpdateAuthor = () => {
const { id } = useParams()
const updateAuthor = updateSingleAuthorMutation(id)
const { data, isLoading } = useGetSingleAuthorQuery(id)
const deleteWebsiteMutation = useDeleteWebsite()
const form = useForm<UpdateAuthorSchemaType>({
resolver: zodResolver(UpdateAuthorSchema),
})
const onSubmit = (values: UpdateAuthorSchemaType) => {
updateAuthor.mutate(values)
}
const handleDeleteWebsite = (index) => {
const website = fields[index];
if (website?.id) {
deleteWebsiteMutation.mutate(website.id, {
onSuccess: () => {
remove(index); // Remove from form UI
form.setValue(
"websites",
fields.filter((_, i) => i !== index)
);
},
});
} else {
remove(index);
}
};
const { fields, append, remove } = useFieldArray({
name: 'websites',
control: form.control
})
useEffect(() => {
if (data && !form.formState.isDirty) {
console.log("Resetting form with new data...");
form.reset({
first_name: data?.first_name || "",
middle_name: data?.middle_name || "",
last_name: data?.last_name || "",
email: data?.email || "",
websites: data?.websites || []
});
}
}, [data, form]);
if (isLoading) {
return <LoadingFallback />
}
// Handle website deletion
return (
<SkeletonWrapper isLoading={isLoading}>
<div className="mt-8 pt-6 border-t">
<h3 className="text-lg font-medium">Author Websites</h3>
<div className="flex items-center justify-between">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => append({ research_resource: "", research_resource_url: "" })}
className="flex items-center gap-2"
>
<Plus className="h-4 w-4" />
Add Website
</Button>
</div>
{fields.map((field, index) => {
return (
<div className="p-4" key={field.id}>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className='flex flex-wrap'>
<Button
type="button"
variant="ghost"
className='mt-7 ml-2'
size="sm"
onClick={() => handleDeleteWebsite(index)}
>
<Trash className='h-4 w-4' />
</Button>
</div>
</div>
</div>
)
})}
</div>
</SkeletonWrapper>
)
react-hook-query.ts
export const useDeleteWebsite = (id?: any) => {
const queryClient = useQueryClient()
const mutation = useMutation({
mutationFn: async (id: string) => {
const response = await axios.delete(`/api/websites/${id}`)
return response.data
},
onSuccess: () => {
console.log("Website deleted, refetching...");
toast.success("Website successfully deleted");
queryClient.invalidateQueries({
queryKey: ['author', id]
});
queryClient.refetchQueries({
queryKey: ['author', id]
});
},
onError: (error: Error | AxiosError) => {
console.error(error)
if (axios.isAxiosError(error)) {
const errorMessage = error.response?.data?.message || "Failed to website paper"
toast.error(errorMessage)
} else {
toast.error("Failed to delete paper")
}
}
})
return mutation
}
api/websites/[id]/route.ts
import { db } from "@/lib/prisma";
import { NextRequest, NextResponse } from "next/server"
export async function DELETE(request: NextRequest, { params }: { params: { id: string } }) {
try {
await db.authors_Website.delete({
where: {
id: params.id
}
})
return NextResponse.json("Successfuly Deleted")
} catch (error) {
return NextResponse.json({ error: "Invalid to delete website" })
}
}
本文标签: typescriptWhy I can39t delete the data if its left aloneStack Overflow
版权声明:本文标题:typescript - Why I can't delete the data if its left alone? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743796375a2540509.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论