Skip to content

Commit

Permalink
fix photo delete
Browse files Browse the repository at this point in the history
  • Loading branch information
kentcdodds committed Sep 14, 2023
1 parent 01ddf9c commit de3e427
Showing 1 changed file with 24 additions and 8 deletions.
32 changes: 24 additions & 8 deletions app/routes/settings+/profile.photo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand All @@ -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()),
Expand All @@ -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 } })
Expand Down Expand Up @@ -155,6 +164,8 @@ export default function PhotoRoute() {
<div className="flex gap-4">
<StatusButton
type="submit"
name="intent"
value="submit"
status={isPending ? 'pending' : actionData?.status ?? 'idle'}
disabled={isPending}
>
Expand All @@ -177,7 +188,12 @@ export default function PhotoRoute() {
selected photo. */}
<ServerOnly>
{() => (
<Button type="submit" className="server-only">
<Button
name="intent"
value="submit"
type="submit"
className="server-only"
>
Save Photo
</Button>
)}
Expand Down

0 comments on commit de3e427

Please sign in to comment.