| 28 | setProfile({ ...profile, [e.target.name]: e.target.value }); |
| 29 | }; |
| 30 | const handleClick = async () => { |
| 31 | try { |
| 32 | const token = localStorage.getItem("token"); |
| 33 | |
| 34 | const config = { |
| 35 | headers: { |
| 36 | "auth-token": token, |
| 37 | }, |
| 38 | }; |
| 39 | |
| 40 | // Update the user profile |
| 41 | const updateProfileResponse = await axios.put( |
| 42 | `${VITE_SERVER_PORT}/api/profile/updateprofile`, |
| 43 | { |
| 44 | name: profile.name, |
| 45 | college: profile.college, |
| 46 | phone: profile.phone, |
| 47 | address: profile.address, |
| 48 | }, |
| 49 | config // Pass the config with headers |
| 50 | ); |
| 51 | |
| 52 | if (updateProfileResponse.status === 200) { |
| 53 | console.log("Profile updated:", updateProfileResponse.data); |
| 54 | |
| 55 | // Reset the profile form after updating |
| 56 | setProfile({ name: "", college: "", phone: "", address: "" }); |
| 57 | |
| 58 | // If there's a file selected (for avatar), upload it |
| 59 | if (file) { |
| 60 | const reader = new FileReader(); |
| 61 | reader.onloadend = () => { |
| 62 | const imageData = reader.result; |
| 63 | axios |
| 64 | .post( |
| 65 | `${VITE_SERVER_PORT}/uploadAvatarImage`, |
| 66 | { image: imageData }, |
| 67 | config // Pass the config with headers for image upload |
| 68 | ) |
| 69 | .then((res) => { |
| 70 | console.log("Image uploaded:", res.data); |
| 71 | // After successful upload, fetch the updated image |
| 72 | axios |
| 73 | .get(`${VITE_SERVER_PORT}/getAvatarImage`, config) // Include config in GET request |
| 74 | .then((res) => { |
| 75 | setImage(res.data[res.data.length - 1].image); // Fetch the last uploaded image |
| 76 | }) |
| 77 | .catch((err) => |
| 78 | console.log("Error fetching avatar image:", err) |
| 79 | ); |
| 80 | }) |
| 81 | .catch((err) => console.log("Error uploading image:", err)); |
| 82 | }; |
| 83 | reader.readAsDataURL(file); // Read the file as Data URL |
| 84 | } |
| 85 | |
| 86 | // Show success alert |
| 87 | props.showAlert("Profile Updated Successfully", "success"); |