Created
June 8, 2024 20:45
-
-
Save sonipranjal/3c0543095f48a4f015718570341e1153 to your computer and use it in GitHub Desktop.
use upload stuff hook -- s3
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
import { useState } from "react"; | |
import axios from "axios"; | |
import { toast } from "sonner"; | |
import { api } from "@/utils/api"; | |
const useUploadStuff = () => { | |
const [isUploadLoading, setIsUploadLoading] = useState(false); | |
const [uploadProgress, setUploadProgress] = useState(0); | |
const getUploadSignedUrl = api.storageRouter.getUploadSignedUrl.useMutation(); | |
const uploadStuff = async ({ | |
stuffFile, | |
saveUrlIntoDBFun, | |
}: { | |
stuffFile: File | undefined; | |
saveUrlIntoDBFun: (url: string) => Promise<void>; | |
}) => { | |
if (!stuffFile) return; | |
try { | |
setIsUploadLoading(true); | |
const { assetUrl, signedUrl } = await getUploadSignedUrl.mutateAsync({ | |
fileMimetype: stuffFile.type, | |
fileName: stuffFile.name, | |
}); | |
await axios | |
.put(signedUrl, stuffFile, { | |
headers: { | |
"Content-Type": stuffFile.type, | |
}, | |
onUploadProgress(progressEvent) { | |
if (progressEvent.progress) { | |
setUploadProgress(Math.floor(progressEvent.progress * 100)); | |
} | |
}, | |
}) | |
.catch((err) => { | |
console.error(err); | |
toast.error("upload failed!"); | |
setIsUploadLoading(false); | |
}); | |
await saveUrlIntoDBFun(assetUrl); | |
setIsUploadLoading(false); | |
} catch (error) { | |
toast.error("uploading failed due to some reason"); | |
setIsUploadLoading(false); | |
} | |
}; | |
return { | |
isUploadLoading, | |
uploadStuff, | |
uploadProgress, | |
}; | |
}; | |
export { useUploadStuff }; |
Author
sonipranjal
commented
Jun 8, 2024
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment