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 committed Dec 14, 2024
1 parent c8963ad commit 2c4b13e
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 43 deletions.
64 changes: 35 additions & 29 deletions src/Utils/request/uploadFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,49 +3,55 @@ 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) {
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!" });
});
} 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
13 changes: 10 additions & 3 deletions src/components/Users/UserAvatar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,13 @@ import uploadFile from "@/Utils/request/uploadFile";
import useTanStackQueryInstead from "@/Utils/request/useQuery";
import { formatDisplayName, sleep } from "@/Utils/utils";

export default function UserAvatar({ username }: { username: string }) {
export default function UserAvatar({
username,
refetchUserData: userDataRefetch,
}: {
username: string;
refetchUserData?: () => void;
}) {
const { t } = useTranslation();
const [editAvatar, setEditAvatar] = useState(false);
const authUser = useAuthUser();
Expand All @@ -43,7 +49,7 @@ 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",
Expand All @@ -54,7 +60,7 @@ export default function UserAvatar({ username }: { username: string }) {
async (xhr: XMLHttpRequest) => {
if (xhr.status === 200) {
await sleep(1000);
refetchUserData();
userDataRefetch?.();
Notification.Success({ msg: t("avatar_updated_success") });
setEditAvatar(false);
}
Expand All @@ -73,6 +79,7 @@ export default function UserAvatar({ username }: { username: string }) {
if (res?.ok) {
Notification.Success({ msg: "Profile picture deleted" });
await refetchUserData();
await userDataRefetch?.();
setEditAvatar(false);
} else {
onError();
Expand Down

0 comments on commit 2c4b13e

Please sign in to comment.