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

Add option to remove profile image #1190

Merged
merged 4 commits into from
Aug 7, 2023
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
26 changes: 26 additions & 0 deletions src/components/EditProfile/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
height: 160px;
width: 160px;
display: flex;
flex-direction: column;
cursor: pointer;
}

Expand Down Expand Up @@ -98,6 +99,30 @@
width: 85% !important;
}

.delete_dp_btn {
display: flex;
justify-content: center;
align-items: center;
margin-top: 10px;
padding: 5px;
cursor: pointer;
border-radius: 8px;
border: none;
background-color: transparent;
color: red;
font-weight: 600;
transition: 0.2s ease-in-out;
}

.delete_dp_btn:hover {
box-shadow: var(--post-box-shadow);
background-color: rgb(223, 219, 219);
}

.delete_dp_btn:active {
background-color: rgb(194, 190, 190);
}

.edit-profile-img {
width: 120px;
aspect-ratio: 1;
Expand All @@ -115,6 +140,7 @@

.edit-profile-save-btn {
width: 100%;
background-color: transparent;
color: rgba(8, 17, 123, 0.69);
font-size: 20px;
font-weight: 600;
Expand Down
183 changes: 104 additions & 79 deletions src/components/EditProfile/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import { useRef, useState } from "react";

import BackIcon from "@mui/icons-material/ArrowBackIosNew";
import { ClickAwayListener } from "@mui/material";
import DeleteIcon from "@mui/icons-material/Delete";
import EditIcon from "@mui/icons-material/Edit";
import blankImg from "../../assets/blank-profile.webp";
import deleteImg from "../../js/deleteImg";
import { useNavigate } from "react-router-dom";
import { useSnackbar } from "notistack";
Expand All @@ -20,7 +22,10 @@ const EditProfile = ({ userData, username, setIsEditing, setUserData }) => {
uid: userData.uid,
});

const user = auth?.currentUser;

const [image, setImage] = useState(null);
const [isUploading, setIsUploading] = useState(false);
const [usernameAvailable, setUsernameAvailable] = useState(true);

const { enqueueSnackbar } = useSnackbar();
Expand Down Expand Up @@ -78,12 +83,62 @@ const EditProfile = ({ userData, username, setIsEditing, setUserData }) => {
}
};

const handleImgSave = () => {
function handleImgDelete() {
setImage("");
setEditedData((prevData) => ({
...prevData,
avatar: "",
}));
}

async function updateUser(url) {
try {
const batch = db.batch();

// Update profile data in authentication (auth)
await auth.currentUser.updateProfile({
displayName: name,
photoURL: url,
});

// Update profile data in users collection
const userRef = db.collection("users").doc(uid);
const userData = {
photoURL: url,
name: name,
username: newUsername,
bio: bio,
country: country,
};
batch.update(userRef, userData);

// Update profile data in all posts
const postsRef = db.collection("posts").where("uid", "==", uid);
const postsSnapshot = await postsRef.get();
postsSnapshot.forEach((post) => {
const postRef = post.ref;
batch.update(postRef, {
avatar: url,
displayName: name,
username: newUsername,
});
});

// Commit the batch
await batch.commit();
} catch (error) {
console.error("Error updating profile:", error);
setIsUploading(false);
throw error;
}
}

const handleProfileUpdate = () => {
if (!usernameAvailable) {
return;
}
const oldImg = userData.avatar;
if (image) {
const oldImg = user.photoURL;
if (image && typeof image === "object") {
const uploadTask = storage.ref(`images/${image?.name}`).put(image);
uploadTask.on(
"state_changed",
Expand All @@ -100,96 +155,50 @@ const EditProfile = ({ userData, username, setIsEditing, setUserData }) => {
.child(image?.name)
.getDownloadURL()
.then(async (url) => {
//Updating profile data in auth
await auth.currentUser.updateProfile({
displayName: name,
photoURL: url,
});

//Updating profile data in users collection
const docRef = db.collection("users").doc(uid);
await docRef.update({
photoURL: url,
name: name,
username: newUsername,
bio: bio,
country: country,
});

//Updating profile data in all posts
const postsRef = db.collection("posts").where("uid", "==", uid);
await postsRef.get().then((postsSnapshot) => {
postsSnapshot.forEach((post) => {
const postRef = post.ref;
postRef.update({
avatar: url,
displayName: name,
username: newUsername,
});
});
});

await deleteImg(oldImg);
oldImg && (await deleteImg(oldImg));
await updateUser(url);
})
.then(
.then(() => {
enqueueSnackbar("Upload Successfull", {
variant: "success",
}),
)
.then(() => setUserData(editedData))
.catch((error) => {
enqueueSnackbar(error, {
variant: "error",
});
setUserData(editedData);
})
.finally(() => {
setIsEditing(false);
setIsUploading(false);
});
},
);
} else if (image?.length === 0) {
async function removeImg() {
oldImg && (await deleteImg(oldImg));
await updateUser(image)
.then(() => {
enqueueSnackbar("Upload Successfull", {
variant: "success",
}),
setUserData(editedData);
})
.finally(() => {
setIsEditing(false);
setIsUploading(false);
});
}
removeImg();
} else {
async function upload() {
//Updating profile data in auth
await auth.currentUser.updateProfile({
displayName: name,
});

//Updating profile data in users collection
const docRef = db.collection("users").doc(uid);
await docRef.update({
name: name,
username: newUsername,
bio: bio,
country: country,
});

//Updating profile data in all posts
const postsRef = db.collection("posts").where("uid", "==", uid);
await postsRef
.get()
.then((postsSnapshot) => {
postsSnapshot.forEach((post) => {
const postRef = post.ref;
postRef.update({
displayName: name,
username: newUsername,
});
});
})
.then(
await updateUser(oldImg)
.then(() => {
enqueueSnackbar("Upload Successfull", {
variant: "success",
}),
)
.then(() => setUserData(editedData))
.then(() => navigate(`/dummygram/user/${newUsername}`))
.catch((error) => {
enqueueSnackbar(error, {
variant: "error",
});
setUserData(editedData);
navigate(`/dummygram/user/${newUsername}`);
})
.finally(() => {
setIsEditing(false);
setIsUploading(false);
});
}
upload();
Expand All @@ -207,9 +216,16 @@ const EditProfile = ({ userData, username, setIsEditing, setUserData }) => {
/>
<h2>Edit Profile</h2>
<div>
<span className="edit-profile-save-btn" onClick={handleImgSave}>
<button
className="edit-profile-save-btn"
onClick={() => {
handleProfileUpdate();
setIsUploading(true);
}}
disabled={isUploading}
>
Save
</span>
</button>
</div>
</div>
<div className="edit-profile-image">
Expand All @@ -220,10 +236,19 @@ const EditProfile = ({ userData, username, setIsEditing, setUserData }) => {
onChange={handleImgChange}
accept="image/*"
/>
<EditIcon className="edit-profile-image-icon" />
<label htmlFor="file">
<img src={avatar} alt={name} className="edit-profile-img" />
<EditIcon className="edit-profile-image-icon" />
</label>
<img
src={avatar?.length > 0 ? avatar : blankImg}
alt={name}
className="edit-profile-img"
/>
{user?.photoURL?.length > 0 && (
<button className="delete_dp_btn" onClick={handleImgDelete}>
<DeleteIcon /> Remove DP
</button>
)}
</div>
<div className="edit-user-details">
{/* name */}
Expand Down
Loading