-
-
Notifications
You must be signed in to change notification settings - Fork 272
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: Extract useUpload into its own reusable hook
- Loading branch information
1 parent
3377969
commit 6b5c597
Showing
3 changed files
with
44 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import { useMutation } from "@tanstack/react-query"; | ||
|
||
import { | ||
ZUploadError, | ||
zUploadErrorSchema, | ||
ZUploadResponse, | ||
zUploadResponseSchema, | ||
} from "@hoarder/shared/types/uploads"; | ||
|
||
export default function useUpload({ | ||
onSuccess, | ||
onError, | ||
}: { | ||
onError?: (e: ZUploadError, req: File) => void; | ||
onSuccess?: (resp: ZUploadResponse, req: File) => Promise<void>; | ||
}) { | ||
return useMutation({ | ||
mutationFn: async (file: File) => { | ||
const formData = new FormData(); | ||
formData.append("file", file); | ||
const resp = await fetch("/api/assets", { | ||
method: "POST", | ||
body: formData, | ||
}); | ||
if (!resp.ok) { | ||
throw new Error(await resp.text()); | ||
} | ||
return zUploadResponseSchema.parse(await resp.json()); | ||
}, | ||
onSuccess: onSuccess, | ||
onError: (error, req) => { | ||
const err = zUploadErrorSchema.parse(JSON.parse(error.message)); | ||
if (onError) { | ||
onError(err, req); | ||
} | ||
}, | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters