Connected picture state to redux
This commit is contained in:
1 parent
223dd280d4
commit
7f57f9fa0c
3 files changed
+88
-44
No files matched your search
@@ -1,5 +1,5 @@
|
|||||||
import { useTheme } from "@emotion/react";
|
import { useTheme } from "@emotion/react";
|
||||||
import { useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
import TabPanel from "@mui/lab/TabPanel";
|
import TabPanel from "@mui/lab/TabPanel";
|
||||||
import { Box, Divider, Modal, Stack, Typography } from "@mui/material";
|
import { Box, Divider, Modal, Stack, Typography } from "@mui/material";
|
||||||
import ButtonSpinner from "../../ButtonSpinner";
|
import ButtonSpinner from "../../ButtonSpinner";
|
||||||
@@ -16,7 +16,7 @@ import { update } from "../../../Features/Auth/authSlice";
|
|||||||
import ImageField from "../../TextFields/Image";
|
import ImageField from "../../TextFields/Image";
|
||||||
import ImageIcon from "@mui/icons-material/Image";
|
import ImageIcon from "@mui/icons-material/Image";
|
||||||
import ProgressUpload from "../../ProgressBars";
|
import ProgressUpload from "../../ProgressBars";
|
||||||
import { bytesToUrl, checkImage, formatBytes } from "../../../Utils/fileUtils";
|
import { bufferTo64, formatBytes } from "../../../Utils/fileUtils";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ProfilePanel component displays a form for editing user profile information
|
* ProfilePanel component displays a form for editing user profile information
|
||||||
@@ -43,7 +43,7 @@ const ProfilePanel = () => {
|
|||||||
//Disabled for now, will revisit in the future
|
//Disabled for now, will revisit in the future
|
||||||
// email: user.email,
|
// email: user.email,
|
||||||
//TODO - upload picture
|
//TODO - upload picture
|
||||||
profilePicUrl: { src: user.profilePicUrl },
|
profileImage: { file: user.profileImage },
|
||||||
});
|
});
|
||||||
const [errors, setErrors] = useState({});
|
const [errors, setErrors] = useState({});
|
||||||
const clearError = (err) => {
|
const clearError = (err) => {
|
||||||
@@ -56,6 +56,26 @@ const ProfilePanel = () => {
|
|||||||
const [isOpen, setIsOpen] = useState("");
|
const [isOpen, setIsOpen] = useState("");
|
||||||
const isModalOpen = (name) => isOpen === name;
|
const isModalOpen = (name) => isOpen === name;
|
||||||
|
|
||||||
|
//maybe move this to Avatar component?
|
||||||
|
const [image, setImage] = useState("");
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchImage = async () => {
|
||||||
|
if (
|
||||||
|
localData.profileImage.file &&
|
||||||
|
localData.profileImage.file.contentType
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const base64 = await bufferTo64(localData.profileImage.file.data);
|
||||||
|
setImage(base64);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error converting buffer to base64:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchImage();
|
||||||
|
}, [localData.profileImage.file]);
|
||||||
|
|
||||||
const handleChange = (event) => {
|
const handleChange = (event) => {
|
||||||
const { value, id } = event.target;
|
const { value, id } = event.target;
|
||||||
const name = idToName[id];
|
const name = idToName[id];
|
||||||
@@ -90,11 +110,12 @@ const ProfilePanel = () => {
|
|||||||
setProgress((prev) => ({ ...prev, isLoading: true }));
|
setProgress((prev) => ({ ...prev, isLoading: true }));
|
||||||
setLocalData((prev) => ({
|
setLocalData((prev) => ({
|
||||||
...prev,
|
...prev,
|
||||||
profilePicUrl: {
|
profileImage: {
|
||||||
|
...prev.profileImage,
|
||||||
name: pic.name,
|
name: pic.name,
|
||||||
type: pic.type,
|
type: pic.type,
|
||||||
size: formatBytes(pic.size),
|
size: formatBytes(pic.size),
|
||||||
src: "",
|
toUpload: pic,
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -116,13 +137,12 @@ const ProfilePanel = () => {
|
|||||||
|
|
||||||
const reader = new FileReader();
|
const reader = new FileReader();
|
||||||
reader.onloadend = () => {
|
reader.onloadend = () => {
|
||||||
const arrayBuffer = reader.result;
|
const base64 = reader.result;
|
||||||
const bytes = new Uint8Array(arrayBuffer);
|
|
||||||
setLocalData((prev) => ({
|
setLocalData((prev) => ({
|
||||||
...prev,
|
...prev,
|
||||||
profilePicUrl: {
|
profileImage: {
|
||||||
...prev.profilePicUrl,
|
...prev.profileImage,
|
||||||
src: bytes,
|
src: base64,
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -136,44 +156,61 @@ const ProfilePanel = () => {
|
|||||||
}
|
}
|
||||||
return { ...prev, value: prev.value + buffer };
|
return { ...prev, value: prev.value + buffer };
|
||||||
});
|
});
|
||||||
}, 150);
|
}, 120);
|
||||||
};
|
};
|
||||||
reader.readAsArrayBuffer(pic);
|
reader.readAsDataURL(pic);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const removePicture = () => {
|
const removePicture = () => {
|
||||||
clearError("picture");
|
clearError("picture");
|
||||||
setLocalData((prev) => ({
|
setLocalData((prev) => ({
|
||||||
...prev,
|
...prev,
|
||||||
profilePicUrl: { src: user.profilePicUrl },
|
profileImage: { file: "" },
|
||||||
}));
|
}));
|
||||||
//interrupt interval if modal closes prior to completing the process
|
//interrupt interval if image upload is canceled prior to completing the process
|
||||||
clearInterval(intervalRef.current);
|
clearInterval(intervalRef.current);
|
||||||
setProgress({ value: 0, isLoading: false });
|
setProgress({ value: 0, isLoading: false });
|
||||||
};
|
};
|
||||||
const closePictureModal = () => {
|
const closePictureModal = () => {
|
||||||
removePicture();
|
clearError("picture");
|
||||||
|
setLocalData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
profileImage: { file: user.profileImage },
|
||||||
|
}));
|
||||||
|
//interrupt interval if modal closes prior to completing the process
|
||||||
|
clearInterval(intervalRef.current);
|
||||||
|
setProgress({ value: 0, isLoading: false });
|
||||||
setIsOpen("");
|
setIsOpen("");
|
||||||
};
|
};
|
||||||
const handleUpdatePicture = () => {
|
const handleUpdatePicture = () => {
|
||||||
setProgress({ value: 0, isLoading: false });
|
setProgress({ value: 0, isLoading: false });
|
||||||
setIsOpen("");
|
setIsOpen("");
|
||||||
};
|
};
|
||||||
|
const handleDeletePicture = () => {
|
||||||
|
setImage(null);
|
||||||
|
setLocalData((prev) => ({
|
||||||
|
...prev,
|
||||||
|
profileImage: { file: "", toUpload: "" },
|
||||||
|
}));
|
||||||
|
};
|
||||||
//TODO - implement delete account function
|
//TODO - implement delete account function
|
||||||
const handleDeleteAccount = () => {};
|
const handleDeleteAccount = () => {};
|
||||||
//TODO - implement save profile function
|
|
||||||
const handleSaveProfile = (event) => {
|
const handleSaveProfile = (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
if (
|
if (
|
||||||
localData.firstname === user.firstname &&
|
localData.firstname === user.firstname &&
|
||||||
localData.lastname === user.lastname &&
|
localData.lastname === user.lastname &&
|
||||||
localData.profilePicUrl === user.profilePicUrl
|
localData.profileImage.toUpload === user.profileImage
|
||||||
) {
|
) {
|
||||||
//TODO - add toast(profile data is unchanged) and maybe disable button
|
//TODO - add toast(profile data is unchanged) and maybe disable button
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
dispatch(update({ authToken, localData }));
|
const toUpdate = {
|
||||||
|
...localData,
|
||||||
|
profileImage: localData.profileImage.toUpload,
|
||||||
|
};
|
||||||
|
dispatch(update({ authToken, toUpdate }));
|
||||||
//TODO - add toast confirmation
|
//TODO - add toast confirmation
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -263,8 +300,10 @@ const ProfilePanel = () => {
|
|||||||
<Stack className="row-stack" direction="row" alignItems="center">
|
<Stack className="row-stack" direction="row" alignItems="center">
|
||||||
<Avatar
|
<Avatar
|
||||||
src={
|
src={
|
||||||
localData.profilePicUrl
|
localData.profileImage?.src
|
||||||
? bytesToUrl(localData.profilePicUrl?.src)
|
? localData.profileImage?.src
|
||||||
|
: image
|
||||||
|
? image
|
||||||
: "/static/images/avatar/2.jpg"
|
: "/static/images/avatar/2.jpg"
|
||||||
}
|
}
|
||||||
firstName={user?.firstname}
|
firstName={user?.firstname}
|
||||||
@@ -279,7 +318,7 @@ const ProfilePanel = () => {
|
|||||||
<Button
|
<Button
|
||||||
level="tertiary"
|
level="tertiary"
|
||||||
label="Delete"
|
label="Delete"
|
||||||
onClick={removePicture}
|
onClick={handleDeletePicture}
|
||||||
/>
|
/>
|
||||||
<Button
|
<Button
|
||||||
level="tertiary"
|
level="tertiary"
|
||||||
@@ -411,15 +450,21 @@ const ProfilePanel = () => {
|
|||||||
</Typography>
|
</Typography>
|
||||||
<ImageField
|
<ImageField
|
||||||
id="update-profile-picture"
|
id="update-profile-picture"
|
||||||
picture={bytesToUrl(localData.profilePicUrl?.src)}
|
picture={
|
||||||
|
localData.profileImage?.src
|
||||||
|
? localData.profileImage?.src
|
||||||
|
: localData.profileImage?.file
|
||||||
|
? image
|
||||||
|
: ""
|
||||||
|
}
|
||||||
loading={progress.isLoading && progress.value !== 100}
|
loading={progress.isLoading && progress.value !== 100}
|
||||||
onChange={handlePicture}
|
onChange={handlePicture}
|
||||||
/>
|
/>
|
||||||
{progress.isLoading || progress.value !== 0 ? (
|
{progress.isLoading || progress.value !== 0 ? (
|
||||||
<ProgressUpload
|
<ProgressUpload
|
||||||
icon={<ImageIcon />}
|
icon={<ImageIcon />}
|
||||||
label={localData.profilePicUrl?.name}
|
label={localData.profileImage?.name}
|
||||||
size={localData.profilePicUrl?.size}
|
size={localData.profileImage?.size}
|
||||||
progress={progress.value}
|
progress={progress.value}
|
||||||
onClick={removePicture}
|
onClick={removePicture}
|
||||||
error={errors["picture"]}
|
error={errors["picture"]}
|
||||||
@@ -434,16 +479,11 @@ const ProfilePanel = () => {
|
|||||||
disabled
|
disabled
|
||||||
sx={{ mr: "auto" }}
|
sx={{ mr: "auto" }}
|
||||||
/>
|
/>
|
||||||
|
<Button level="tertiary" label="Remove" onClick={removePicture} />
|
||||||
<Button
|
<Button
|
||||||
level="tertiary"
|
|
||||||
label="Remove"
|
|
||||||
onClick={removePicture}
|
|
||||||
/>
|
|
||||||
<ButtonSpinner
|
|
||||||
level="primary"
|
level="primary"
|
||||||
label="Update"
|
label="Update"
|
||||||
onClick={handleUpdatePicture}
|
onClick={handleUpdatePicture}
|
||||||
isLoading={isLoading}
|
|
||||||
disabled={
|
disabled={
|
||||||
(Object.keys(errors).length !== 0 && errors?.picture) ||
|
(Object.keys(errors).length !== 0 && errors?.picture) ||
|
||||||
progress.value !== 100
|
progress.value !== 100
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ export const login = createAsyncThunk("auth/login", async (form, thunkApi) => {
|
|||||||
export const update = createAsyncThunk(
|
export const update = createAsyncThunk(
|
||||||
"auth/update",
|
"auth/update",
|
||||||
async (data, thunkApi) => {
|
async (data, thunkApi) => {
|
||||||
const { authToken: token, localData: form } = data;
|
const { authToken: token, toUpdate: form } = data;
|
||||||
const user = jwtDecode(token);
|
const user = jwtDecode(token);
|
||||||
try {
|
try {
|
||||||
//1.5s delay to show loading spinner
|
//1.5s delay to show loading spinner
|
||||||
@@ -50,7 +50,7 @@ export const update = createAsyncThunk(
|
|||||||
const res = await axios.post(`${BASE_URL}/auth/user/${user._id}`, form, {
|
const res = await axios.post(`${BASE_URL}/auth/user/${user._id}`, form, {
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${token}`,
|
Authorization: `Bearer ${token}`,
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "multipart/form-data",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
return res.data;
|
return res.data;
|
||||||
|
|||||||
@@ -1,13 +1,3 @@
|
|||||||
import { useMemo } from "react";
|
|
||||||
|
|
||||||
export const bytesToUrl = (bytes) => {
|
|
||||||
return useMemo(() => {
|
|
||||||
const blob = new Blob([bytes], { type: "image/jpeg" });
|
|
||||||
const url = URL.createObjectURL(blob);
|
|
||||||
return url;
|
|
||||||
}, [bytes]);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const formatBytes = (bytes) => {
|
export const formatBytes = (bytes) => {
|
||||||
if (bytes === 0) return "0 Bytes";
|
if (bytes === 0) return "0 Bytes";
|
||||||
const megabytes = bytes / (1024 * 1024);
|
const megabytes = bytes / (1024 * 1024);
|
||||||
@@ -17,5 +7,19 @@ export const formatBytes = (bytes) => {
|
|||||||
export const checkImage = (url) => {
|
export const checkImage = (url) => {
|
||||||
const img = new Image();
|
const img = new Image();
|
||||||
img.src = url;
|
img.src = url;
|
||||||
return img.naturalWidth !==0;
|
return img.naturalWidth !== 0;
|
||||||
}
|
};
|
||||||
|
|
||||||
|
export const bufferTo64 = (bufferData) => {
|
||||||
|
const uint8Array = new Uint8Array(bufferData.data);
|
||||||
|
const blob = new Blob([uint8Array], { type: bufferData.contentType });
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onloadend = () => {
|
||||||
|
resolve(reader.result);
|
||||||
|
};
|
||||||
|
reader.readAsDataURL(blob);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
Reference in new issue
Block a user