Skip to content

Instantly share code, notes, and snippets.

@usmansbk
Last active July 19, 2022 07:29
Show Gist options
  • Save usmansbk/a334acd3c56332ceb167f203f09811f7 to your computer and use it in GitHub Desktop.
Save usmansbk/a334acd3c56332ceb167f203f09811f7 to your computer and use it in GitHub Desktop.
import { useCallback, useState } from "react";
import { Platform } from "react-native";
import { ImageInfo } from "expo-image-picker";
import * as mime from "mime";
export default function useUploadAvatar() {
const [uploading, setUploading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const [data, setData] = useState(null);
const { accessToken } = useAuth();
const upload = useCallback(async ({ uri }: ImageInfo) => {
setUploading(true);
try {
let file;
if (Platform.OS === "web") {
const img = await fetch(uri);
const blob = await img.blob();
const mimeStartAt = uri.indexOf("image/");
const mimeEndAt = uri.indexOf(";");
const mimetype = uri.slice(mimeStartAt, mimeEndAt);
file = new File([blob], "avatar", {
type: mimetype,
});
} else {
file = {
uri,
type: mime.getType(uri),
name: uri.split("/").pop(),
};
}
const formData = new FormData();
formData.append("avatar", file as Blob);
const UPLOAD_ENDPOINT = "https://api-upload-endpoint";
let accessToken = "my-access-token";
const response = await fetch(UPLOAD_ENDPOINT, {
method: "POST",
body: formData,
headers: {
Accept: "application/json",
authorization: accessToken ? `Bearer ${accessToken}` : "",
},
});
const json = await response.json();
setData(json);
} catch (e) {
setError(e as Error);
} finally {
setUploading(false);
}
}, []);
return {
uploading,
upload,
error,
data,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment