From de3e4271119eea6f46f7e48540776ab941be5581 Mon Sep 17 00:00:00 2001 From: "Kent C. Dodds" Date: Thu, 14 Sep 2023 14:12:52 -0600 Subject: [PATCH] fix photo delete --- app/routes/settings+/profile.photo.tsx | 32 +++++++++++++++++++------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/app/routes/settings+/profile.photo.tsx b/app/routes/settings+/profile.photo.tsx index 0d85cc24..5fc95aa6 100644 --- a/app/routes/settings+/profile.photo.tsx +++ b/app/routes/settings+/profile.photo.tsx @@ -30,13 +30,20 @@ export const handle = { const MAX_SIZE = 1024 * 1024 * 3 // 3MB -const PhotoFormSchema = z.object({ +const DeleteImageSchema = z.object({ + intent: z.literal('delete'), +}) + +const SubmitFormSchema = z.object({ + intent: z.literal('submit'), photoFile: z .instanceof(File) .refine(file => file.size > 0, 'Image is required') .refine(file => file.size <= MAX_SIZE, 'Image size must be less than 3MB'), }) +const PhotoFormSchema = z.union([DeleteImageSchema, SubmitFormSchema]) + export async function loader({ request }: DataFunctionArgs) { const userId = await requireUserId(request) const user = await prisma.user.findUnique({ @@ -58,16 +65,13 @@ export async function action({ request }: DataFunctionArgs) { request, unstable_createMemoryUploadHandler({ maxPartSize: MAX_SIZE }), ) - const intent = formData.get('intent') - if (intent === 'delete') { - await prisma.userImage.deleteMany({ where: { userId } }) - return redirect('/settings/profile') - } const submission = await parse(formData, { schema: PhotoFormSchema.transform(async data => { + if (data.intent === 'delete') return { intent: 'delete' } if (data.photoFile.size <= 0) return z.NEVER return { + intent: data.intent, image: { contentType: data.photoFile.type, blob: Buffer.from(await data.photoFile.arrayBuffer()), @@ -84,7 +88,12 @@ export async function action({ request }: DataFunctionArgs) { return json({ status: 'error', submission } as const, { status: 400 }) } - const { image } = submission.value + const { image, intent } = submission.value + + if (intent === 'delete') { + await prisma.userImage.deleteMany({ where: { userId } }) + return redirect('/settings/profile') + } await prisma.$transaction(async $prisma => { await $prisma.userImage.deleteMany({ where: { userId } }) @@ -155,6 +164,8 @@ export default function PhotoRoute() {
@@ -177,7 +188,12 @@ export default function PhotoRoute() { selected photo. */} {() => ( - )}