Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix avatar upload stuck state and update header after changing avatar #9427

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -19,20 +19,25 @@ 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,
}: {
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,
},
rithviknishad marked this conversation as resolved.
Show resolved Hide resolved
},
});
);

if (isLoading || !userData) {
return <Loading />;
Expand All @@ -43,7 +48,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 +59,7 @@ export default function UserAvatar({ username }: { username: string }) {
async (xhr: XMLHttpRequest) => {
if (xhr.status === 200) {
await sleep(1000);
refetchUserData();
refetchUserData?.();
Notification.Success({ msg: t("avatar_updated_success") });
setEditAvatar(false);
}
Expand All @@ -72,7 +77,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
Loading