Skip to content

Commit

Permalink
Fix avatar upload stuck state and update header after changing avatar (
Browse files Browse the repository at this point in the history
  • Loading branch information
shauryag2002 authored Dec 18, 2024
1 parent 4a560f4 commit 1d50f53
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 52 deletions.
69 changes: 40 additions & 29 deletions src/Utils/request/uploadFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,49 +3,60 @@ import { Dispatch, SetStateAction } from "react";
import * as Notification from "@/Utils/Notifications";
import { handleUploadPercentage } from "@/Utils/request/utils";

const uploadFile = (
const uploadFile = async (
url: string,
file: File | FormData,
reqMethod: string,
headers: object,
onLoad: (xhr: XMLHttpRequest) => void,
setUploadPercent: Dispatch<SetStateAction<number>> | null,
onError: () => void,
) => {
const xhr = new XMLHttpRequest();
xhr.open(reqMethod, url);
): Promise<void> => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(reqMethod, url);

Object.entries(headers).forEach(([key, value]) => {
xhr.setRequestHeader(key, value);
});
Object.entries(headers).forEach(([key, value]) => {
xhr.setRequestHeader(key, value);
});

xhr.onload = () => {
onLoad(xhr);
if (400 <= xhr.status && xhr.status <= 499) {
const error = JSON.parse(xhr.responseText);
if (typeof error === "object" && !Array.isArray(error)) {
Object.values(error).forEach((msg) => {
Notification.Error({ msg: msg || "Something went wrong!" });
});
xhr.onload = () => {
onLoad(xhr);
if (400 <= xhr.status && xhr.status <= 499) {
let error;
try {
error = JSON.parse(xhr.responseText);
} catch {
error = xhr.responseText;
}
if (typeof error === "object" && !Array.isArray(error)) {
Object.values(error).forEach((msg) => {
Notification.Error({ msg: msg || "Something went wrong!" });
});
} else {
Notification.Error({ msg: error || "Something went wrong!" });
}
reject(new Error("Client error"));
} else {
Notification.Error({ msg: error || "Something went wrong!" });
resolve();
}
};

if (setUploadPercent != null) {
xhr.upload.onprogress = (event: ProgressEvent) => {
handleUploadPercentage(event, setUploadPercent);
};
}
};

if (setUploadPercent != null) {
xhr.upload.onprogress = (event: ProgressEvent) => {
handleUploadPercentage(event, setUploadPercent);
xhr.onerror = () => {
Notification.Error({
msg: "Network Failure. Please check your internet connectivity.",
});
onError();
reject(new Error("Network error"));
};
}

xhr.onerror = () => {
Notification.Error({
msg: "Network Failure. Please check your internet connectivity.",
});
onError();
};
xhr.send(file);
xhr.send(file);
});
};

export default uploadFile;
27 changes: 16 additions & 11 deletions src/components/Common/AvatarEditModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,20 +114,25 @@ const AvatarEditModal = ({
};

const uploadAvatar = async () => {
if (!selectedFile) {
closeModal();
return;
}
try {
if (!selectedFile) {
closeModal();
return;
}

setIsProcessing(true);
setIsCaptureImgBeingUploaded(true);
await handleUpload(selectedFile, () => {
setSelectedFile(undefined);
setPreview(undefined);
setPreviewImage(null);
setIsProcessing(true);
setIsCaptureImgBeingUploaded(true);
await handleUpload(selectedFile, () => {
setSelectedFile(undefined);
setPreview(undefined);
setPreviewImage(null);
setIsCaptureImgBeingUploaded(false);
setIsProcessing(false);
});
} finally {
setIsCaptureImgBeingUploaded(false);
setIsProcessing(false);
});
}
};

const deleteAvatar = async () => {
Expand Down
29 changes: 17 additions & 12 deletions src/components/Users/UserAvatar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,25 @@ import useTanStackQueryInstead from "@/Utils/request/useQuery";
import { getAuthorizationHeader } from "@/Utils/request/utils";
import { formatDisplayName, sleep } from "@/Utils/utils";

export default function UserAvatar({ username }: { username: string }) {
export default function UserAvatar({
username,
refetchUserData,
}: {
username: string;
refetchUserData?: () => void;
}) {
const { t } = useTranslation();
const [editAvatar, setEditAvatar] = useState(false);
const authUser = useAuthUser();

const {
data: userData,
loading: isLoading,
refetch: refetchUserData,
} = useTanStackQueryInstead(routes.getUserDetails, {
pathParams: {
username: username,
const { data: userData, loading: isLoading } = useTanStackQueryInstead(
routes.getUserDetails,
{
pathParams: {
username: username,
},
},
});
);

if (isLoading || !userData) {
return <Loading />;
Expand All @@ -42,15 +47,15 @@ export default function UserAvatar({ username }: { username: string }) {
formData.append("profile_picture", file);
const url = `${careConfig.apiUrl}/api/v1/users/${userData.username}/profile_picture/`;

uploadFile(
await uploadFile(
url,
formData,
"POST",
{ Authorization: getAuthorizationHeader() },
async (xhr: XMLHttpRequest) => {
if (xhr.status === 200) {
await sleep(1000);
refetchUserData();
refetchUserData?.();
Notification.Success({ msg: t("avatar_updated_success") });
setEditAvatar(false);
}
Expand All @@ -68,7 +73,7 @@ export default function UserAvatar({ username }: { username: string }) {
});
if (res?.ok) {
Notification.Success({ msg: "Profile picture deleted" });
await refetchUserData();
refetchUserData?.();
setEditAvatar(false);
} else {
onError();
Expand Down

0 comments on commit 1d50f53

Please sign in to comment.