Skip to content

Commit

Permalink
fixed user profile error
Browse files Browse the repository at this point in the history
  • Loading branch information
AyushSharma72 committed Oct 24, 2024
1 parent 0758ce4 commit 66afe53
Show file tree
Hide file tree
Showing 3 changed files with 228 additions and 124 deletions.
320 changes: 210 additions & 110 deletions client/src/component/EditProfile.jsx
Original file line number Diff line number Diff line change
@@ -1,125 +1,225 @@
import { useContext, useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { Button } from 'react-bootstrap';
import axios from 'axios'
import profileContext from '../context/profileContext';
import userDummyImg from '../assets/images/User/User.png'
import { useContext, useEffect, useState } from "react";
import PropTypes from "prop-types";
import { Button } from "react-bootstrap";
import axios from "axios";
import profileContext from "../context/profileContext";
import userDummyImg from "../assets/images/User/User.png";
// CSS
import '../css/EditProfile.css';
import "../css/EditProfile.css";

const EditProfile = (props) => {
const VITE_SERVER_PORT = import.meta.env.VITE_SERVER_PORT || 'https://bitbox-uxbo.onrender.com';
const userProfileContext = useContext(profileContext);
const { updateUserProfile } = userProfileContext;
const VITE_SERVER_PORT =
import.meta.env.VITE_SERVER_PORT || "https://bitbox-uxbo.onrender.com";
const userProfileContext = useContext(profileContext);
const { updateUserProfile } = userProfileContext;

const [profile, setProfile] = useState({ name: '', college: '', phone: '', address: '' });
const [profile, setProfile] = useState({
name: "",
college: "",
phone: "",
address: "",
});

const handleKeyDown = (e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleClick();
}
const handleKeyDown = (e) => {
if (e.key === "Enter") {
e.preventDefault();
handleClick();
}
};

const onChange = (e) => {
setProfile({ ...profile, [e.target.name]: e.target.value });
};

const handleClick = async () => {
try {
// also update the user profile
const updateProfileResponse = await axios.put(
`http://localhost:5000/api/profile/updateprofile`,
{
name: profile.name,
college: profile.college,
phone: profile.phone,
address: profile.address,
}
);

if (updateProfileResponse.status === 200) {
console.log("Profile updated:", updateProfileResponse.data);

const onChange = (e) => {
setProfile({ ...profile, [e.target.name]: e.target.value });
};

const handleClick = async () => {
try {
updateUserProfile(profile.name, profile.college, profile.phone, profile.address);
setProfile({ name: "", college: "", phone: "", address: "" });
const reader = new FileReader();
reader.onloadend = () => {
const imageData = reader.result;
axios.post(`${VITE_SERVER_PORT}/uploadAvatarImage`, { image: imageData })
.then(res => {
console.log(res)
// After successful upload, fetch the updated image
axios.get(`${VITE_SERVER_PORT}/getAvatarImage`)
.then(res => setImage(res.data[res.data.length - 1].image)) // Fetch the last uploaded image
.catch(err => console.log(err))
})
.catch(err => console.log(err))
}
reader.readAsDataURL(file);
props.showAlert("Profile Updated Successfully", "success");
} catch (error) {
props.showAlert("Profile Updated Failed", "danger");
// Reset the profile form after updating
setProfile({ name: "", college: "", phone: "", address: "" });

// If there's a file selected (for avatar), upload it
if (file) {
const reader = new FileReader();
reader.onloadend = () => {
const imageData = reader.result;
axios
.post(`${VITE_SERVER_PORT}/uploadAvatarImage`, {
image: imageData,
})
.then((res) => {
console.log("Image uploaded:", res.data);
// After successful upload, fetch the updated image
axios
.get(`${VITE_SERVER_PORT}/getAvatarImage`)
.then((res) => {
setImage(res.data[res.data.length - 1].image); // Fetch the last uploaded image
})
.catch((err) =>
console.log("Error fetching avatar image:", err)
);
})
.catch((err) => console.log("Error uploading image:", err));
};
reader.readAsDataURL(file); // Read the file as Data URL
}
};

// For Avatar Uploading
const [file, setFile] = useState()
const [image, setImage] = useState()

useEffect(() => {
// Fetch initial image when component mounts
axios.get(`{host}/getAvatarImage`)
.then(res => setImage(res.data[res.data.length - 1].image)) // Fetch the last uploaded image
.catch(err => console.log(err))
}, [])

return (
<div>
<div className='editprofile-main-container'>
<div className="row">
<div className="col-md-3 editprofile-avatar-container">
<h2>Edit Details</h2>
<div className="text-center">
{image ? (
<img src={image}
className="avatar img-circle"
alt="avatar"
/>
) : (
<img
src={userDummyImg}
className="avatar img-circle"
alt="avatar"
/>
)}
<input type="file" className="form-control mt-2" style={{ color: props.mode === 'dark' ? 'black' : '' }} onChange={e => setFile(e.target.files[0])} />
</div>
</div>
<div className="col-md-9 editprofile-info-container">
<h2 className='Heading-Page'>Personal info</h2>
<div className="col-lg-8 pb-5">
<div>
<div className="mb-3">
<label htmlFor="name" className="form-label">Full Name</label>
<input autoFocus type="text" className="form-control" placeholder="Enter your full name" id="name" name='name' value={profile.name} onChange={onChange} required onKeyDown={handleKeyDown} />
</div>

<div className="mb-3">
<label htmlFor="address" className="form-label">Address</label>
<input autoFocus type="text" className="form-control" placeholder="Enter your address" id="address" name='address' value={profile.address} onChange={onChange} required onKeyDown={handleKeyDown} />
</div>

<div className="mb-3">
<label htmlFor="college" className="form-label">College</label>
<input autoFocus type="text" className="form-control" placeholder="Enter your college name" id="college" name='college' value={profile.college} onChange={onChange} required onKeyDown={handleKeyDown} />
</div>

<div className="mb-3">
<label htmlFor="phone" className="form-label">Phone Number</label>
<input autoFocus type="text" className="form-control" placeholder="Enter your phone number" id="phone" name='phone' value={profile.phone} onChange={onChange} required onKeyDown={handleKeyDown} />
</div>
<div className='flex justify-content-center'>
<Button variant="primary" style={{ width: "100%" }} onClick={handleClick}>Update Profile</Button>
</div>
</div>
</div>
</div>

// Show success alert
props.showAlert("Profile Updated Successfully", "success");
} else {
// If profile update failed
props.showAlert("Profile Update Failed", "danger");
}
} catch (error) {
console.error("Error updating profile or uploading image:", error);
props.showAlert("Profile Update Failed", "danger");
}
};

// For Avatar Uploading
const [file, setFile] = useState();
const [image, setImage] = useState();

useEffect(() => {
// Fetch initial image when component mounts
axios
.get(`{host}/getAvatarImage`)
.then((res) => setImage(res.data[res.data.length - 1].image)) // Fetch the last uploaded image
.catch((err) => console.log(err));
}, []);

return (
<div>
<div className="editprofile-main-container">
<div className="row">
<div className="col-md-3 editprofile-avatar-container">
<h2>Edit Details</h2>
<div className="text-center">
{image ? (
<img src={image} className="avatar img-circle" alt="avatar" />
) : (
<img
src={userDummyImg}
className="avatar img-circle"
alt="avatar"
/>
)}
<input
type="file"
className="form-control mt-2"
style={{ color: props.mode === "dark" ? "black" : "" }}
onChange={(e) => setFile(e.target.files[0])}
/>
</div>
</div>
<div className="col-md-9 editprofile-info-container">
<h2 className="Heading-Page">Personal info</h2>
<div className="col-lg-8 pb-5">
<div>
<div className="mb-3">
<label htmlFor="name" className="form-label">
Full Name
</label>
<input
autoFocus
type="text"
className="form-control"
placeholder="Enter your full name"
id="name"
name="name"
value={profile.name}
onChange={onChange}
required
onKeyDown={handleKeyDown}
/>
</div>

<div className="mb-3">
<label htmlFor="address" className="form-label">
Address
</label>
<input
autoFocus
type="text"
className="form-control"
placeholder="Enter your address"
id="address"
name="address"
value={profile.address}
onChange={onChange}
required
onKeyDown={handleKeyDown}
/>
</div>

<div className="mb-3">
<label htmlFor="college" className="form-label">
College
</label>
<input
autoFocus
type="text"
className="form-control"
placeholder="Enter your college name"
id="college"
name="college"
value={profile.college}
onChange={onChange}
required
onKeyDown={handleKeyDown}
/>
</div>

<div className="mb-3">
<label htmlFor="phone" className="form-label">
Phone Number
</label>
<input
autoFocus
type="text"
className="form-control"
placeholder="Enter your phone number"
id="phone"
name="phone"
value={profile.phone}
onChange={onChange}
required
onKeyDown={handleKeyDown}
/>
</div>
<div className="flex justify-content-center">
<Button
variant="primary"
style={{ width: "100%" }}
onClick={handleClick}
>
Update Profile
</Button>
</div>
</div>
</div>
</div>
</div>
);
}
</div>
</div>
);
};

EditProfile.propTypes = {
showAlert: PropTypes.func,
mode: PropTypes.string,
onUpdateProfile: PropTypes.func, // Function to notify parent about profile update
showAlert: PropTypes.func,
mode: PropTypes.string,
onUpdateProfile: PropTypes.func, // Function to notify parent about profile update
};
export default EditProfile;
30 changes: 17 additions & 13 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@ const { Server } = require("socket.io");
const connectToMongo = require("./db");
const cors = require("cors");
const Avatar = require("./Models/Avatar");
require('dotenv').config(); // Load environment variables from .env file
require("dotenv").config(); // Load environment variables from .env file

// Connect to MongoDB
connectToMongo();

const app = express();
const app = express();
const httpServer = require("http").createServer(app);
const io = new Server(httpServer, {
cors: {
origin: "*", // Update to specific origins in production
methods: ['GET', 'POST', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
methods: ["GET", "POST", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization"],
},
});

Expand All @@ -28,10 +28,12 @@ app.use((req, res, next) => {
});

// Set up CORS middleware
app.use(cors({
origin: "*", // Update to specific origins in production
methods: ['GET', 'POST', 'OPTIONS'],
}));
app.use(
cors({
origin: "*", // Update to specific origins in production
methods: ["GET", "POST", "OPTIONS", "PUT"],
})
);

// Middleware to parse JSON requests
app.use(express.json());
Expand Down Expand Up @@ -66,11 +68,13 @@ io.on("connection", (socket) => {
});

// Start HTTP server - listen on the correct PORT
httpServer.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
}).on('error', (err) => {
console.error('Server error:', err);
});
httpServer
.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
})
.on("error", (err) => {
console.error("Server error:", err);
});

// Centralized error-handling middleware
app.use((err, req, res, next) => {
Expand Down
Loading

0 comments on commit 66afe53

Please sign in to comment.