Browse Source

delete recently added images if edit is cancelled. Also remove some console.logs

Ramona Plogmann 1 year ago
parent
commit
27126f2371

+ 8 - 8
client/src/components/Images/ImageUpload.jsx

@@ -9,6 +9,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
 import { faCamera, faCircle } from "@fortawesome/free-solid-svg-icons";
 import CircleImage from "./CircleImage";
 import CircularProgress from "@material-ui/core/CircularProgress";
+import { deleteSingleImage } from "./images.util";
 
 const serverURL = process.env.REACT_APP_SERVER_URL;
 
@@ -173,14 +174,13 @@ const ImageUpload = (props) => {
   }
 
   const deleteImage = (image) => {
-    axios.post(serverURL + "/images/deleteImage", image)
-         .then(res => {
-           const newUploadedImages = uploadedImages.filter(i => i !== image);
-           if (image.isMain && newUploadedImages.length > 0) {
-             newUploadedImages[0].isMain = true;
-           }
-           onChangeUploadedImages(newUploadedImages);
-         }).catch(err => {console.log(err)});
+    deleteSingleImage(image, () => {
+      const newUploadedImages = uploadedImages.filter(i => i !== image);
+      if (image.isMain && newUploadedImages.length > 0) {
+        newUploadedImages[0].isMain = true;
+      }
+      onChangeUploadedImages(newUploadedImages);
+    });
   }
 
   const chooseImageAsMain = (image) => {

+ 10 - 0
client/src/components/Images/images.util.jsx

@@ -0,0 +1,10 @@
+import axios from "axios";
+
+const serverURL = process.env.REACT_APP_SERVER_URL;
+
+export const deleteSingleImage = (image, callback = null) => {
+  axios.post(serverURL + "/images/deleteImage", image)
+       .then(res => {
+         if(callback) callback();
+       }).catch(err => {console.log(err)});
+}

+ 8 - 6
client/src/components/Meals/AddMeal.jsx

@@ -90,14 +90,16 @@ const AddMeal = () => {
     addMeal(meal, onDoneAdding);
   }
 
+  const goBackAndDeleteImagesFromMeal = () => {
+    if (meal.images && meal.images.length > 0) {
+      deleteAllImagesFromMeal(meal._id);
+    }
+    navigate(-1);
+  }
+
   return (
     <>
-      <Navbar pageTitle={t('New Meal')} leftSideComponent={<BackButton onClick={() => {
-        if (meal.images && meal.images.length > 0) {
-          deleteAllImagesFromMeal(meal._id);
-        }
-        navigate(-1);
-      }} />} rightSideComponent={meal.title && !isLoading ? <DoneButton onClick={addNewMeal} /> : null} />
+      <Navbar pageTitle={t('New Meal')} leftSideComponent={<BackButton onClick={goBackAndDeleteImagesFromMeal} />} rightSideComponent={meal.title && !isLoading ? <DoneButton onClick={addNewMeal} /> : null} />
 
       <form noValidate onSubmit={addNewMeal} className={classes.form}>
         <EditMealCore updateMeal={updateMeal} meal={meal} autoFocusFirstInput setImagesLoading={setIsLoading} setLoadingImagesTakesLong={setLoadingImagesTakesLong} />

+ 19 - 3
client/src/components/Meals/EditMeal.jsx

@@ -14,6 +14,7 @@ import Loading from "../Loading";
 import DoneButton from "../Buttons/DoneButton";
 import { useLocation, useNavigate, useParams } from "react-router-dom";
 import SavingButton from "../Buttons/SavingButton";
+import { deleteSingleImage } from "../Images/images.util";
 
 const useStyles = makeStyles((theme) => ({
   form: {
@@ -58,12 +59,16 @@ const EditMeal = () => {
   let { mealId } = useParams();
 
   const [meal, setMeal] = useState();
+  const [originalMealImages, setOriginalMealImages] = useState([]);
   const [imagesLoading, setImagesLoading] = useState(false);
   const [loadingImagesTakesLong, setLoadingImagesTakesLong] = useState(false);
   const [isSaving, setIsSaving] = useState(false);
 
   useEffect(() => {
-    fetchAndUpdateMeal(mealId, setMeal);
+    fetchAndUpdateMeal(mealId, (mealFromDB) => {
+      setMeal(mealFromDB);
+      if(mealFromDB.images) setOriginalMealImages(Array.from(mealFromDB.images));
+    });
   }, [mealId]);
 
   // set the meal that is given in state as a temporary option while the one from the server is loaded
@@ -81,7 +86,7 @@ const EditMeal = () => {
   const deleteMeal = () => {
     axios.post(serverURL + '/meals/delete/' + meal._id).then((result) => {
       const deletedMeal = result.data.meal;
-      console.log('delete request sent for meal ', deletedMeal._id);
+      // console.log('delete request sent for meal ', deletedMeal._id);
       navigate('../', {
         state: {
           snackbar: {
@@ -98,7 +103,7 @@ const EditMeal = () => {
     setIsSaving(true);
     if (meal.title) {
       axios.post(serverURL + '/meals/edit/' + meal._id, meal).then((result) => {
-        console.log('edit request sent', result.data);
+        // console.log('edit request sent', result.data);
         setIsSaving(false);
         navigate(-1, { state: { meal: result.data.meal } });
       });
@@ -106,6 +111,17 @@ const EditMeal = () => {
   }
 
   const closeEdit = () => {
+    // delete images that should not be saved
+    const imagesToDelete = meal.images.filter(i => !originalMealImages.includes(i));
+    if(imagesToDelete.length > 0) {
+      imagesToDelete.forEach(image => {
+        deleteSingleImage(image, () => {console.log('deleted', image)});
+      });
+    }
+
+    // todo right now images that get deleted do not get restored when cancel is clicked.
+    //  might consider either doing that or deleting them only on save
+
     navigate(-1, { state: { meal } });
   }
 

+ 1 - 1
client/src/components/Meals/EditMealCore.jsx

@@ -38,7 +38,7 @@ const EditMealCore = (props) => {
   const [loadingImagesTakesLongTimeout, setLoadingImagesTakesLongTimeout] = useState(0);
 
   const onChangeUploadedImages = (newUploadedImages) => {
-    console.log('updated uploadedImages', newUploadedImages);
+    // console.log('updated uploadedImages', newUploadedImages);
     updateMeal('images', Array.from(newUploadedImages));
   }
 

+ 1 - 2
client/src/components/Meals/SelectMealTags.jsx

@@ -37,8 +37,7 @@ const SelectMealTags = (props) => {
 
   if (shouldBeTranslated) {
     const tagsNotTranslated = allTags.filter(tag => !translationsMap.has(tag));
-    console.log('allTags', allTags);
-    console.log('translation missing for ' + tagsNotTranslated.length, tagsNotTranslated);
+    // console.log('translation missing for ' + tagsNotTranslated.length, tagsNotTranslated);
     if (tagsNotTranslated.length > 0) {
       // translate tags
       translateThingsAndAddToMap(tagsNotTranslated);

+ 1 - 1
client/src/components/Meals/meals.util.jsx

@@ -49,7 +49,7 @@ export const addMeal = (meal, callback) => {
   if (meal.title) {
     axios.post(serverURL + '/meals/add', meal, {})
          .then(res => {
-           console.log('added meal', res);
+           // console.log('added meal', res);
            if (callback) callback();
          }).catch(err => {console.log(err)});
   }

+ 1 - 1
client/src/components/Plans/AddPlanItem.jsx

@@ -53,7 +53,7 @@ const AddPlanItem = (props) => {
 
   const addNewPlan = (event) => {
     event.preventDefault();
-    console.log('adding ' + planItem.title + ' with connected planItem', planItem.connectedMeal);
+    // console.log('adding ' + planItem.title + ' with connected planItem', planItem.connectedMeal);
     if (planItem.title && user) {
       const newPlan = {
         userId: user.sub,

+ 1 - 1
client/src/components/Settings/EditProfile.jsx

@@ -110,7 +110,7 @@ const EditProfile = () => {
 
   const updateProfileImage = (image) => {
     const imageSrc = image.url;
-    console.log('set uploaded source', imageSrc);
+    // console.log('set uploaded source', imageSrc);
     setProfileImage(imageSrc);
     updateProfileImageInMetadata(imageSrc);
   }

+ 2 - 3
client/src/components/Settings/settings.util.jsx

@@ -14,7 +14,7 @@ export const createNewSettingsForUser = (userId, callback) => {
     const newSettings = { userId: userId };
     axios.post(serverURL + '/settings/add/', newSettings)
          .then(res => {
-           console.log('result of adding settings for ' + userId, res);
+           // console.log('result of adding settings for ' + userId, res);
            if (callback) callback(res.data);
          }).catch(err => {console.log(err)});
   }
@@ -27,10 +27,9 @@ export const createNewSettingsForUser = (userId, callback) => {
  * @param {function} callback function to be executed after updating (receives new updated data)
  */
 export const updateUser = (userId, newData, callback) => {
-  console.log('this is my function');
   axios.put(serverURL + '/users/update/' + userId, newData)
        .then((result) => {
-         console.log('updated user', result.data);
+         // console.log('updated user', result.data);
          if (callback) callback(result.data);
        }).catch(err => {console.log(err)});
 }

+ 2 - 2
client/src/components/util/translation/useTranslationMap.jsx

@@ -24,11 +24,11 @@ export function useTranslationsMap(isInUse = true) {
     if (thingsToTranslate.length > 0) { // avoid API call if there is nothing to translate
       googleTranslate(thingsToTranslate, i18n.language, (translations) => {
         thingsToTranslate.forEach((value, index) => {
-          console.log(index, value, translations[index]);
+          // console.log(index, value, translations[index]);
           addToTranslationsMap(value, translations[index]);
         });
         if (callback) callback();
-        console.log('Map created from', thingsToTranslate, translations);
+        // console.log('Map created from', thingsToTranslate, translations);
       });
     } else {
       if (callback) callback();

+ 3 - 3
server/controllers/images.controllers.js

@@ -66,7 +66,7 @@ export const uploadSingleImage = async (req, res) => {
     try {
       // try to delete an already existing profile picture since it just gets replaced on cloudinary and then save the new one
       Image.findOneAndDelete({categoryName: 'userProfile', cloudinaryPublicId: public_id}).then((deletedImaged) => {
-        console.log('replaced', deletedImaged, 'with', newImage);
+        // console.log('replaced', deletedImaged, 'with', newImage);
         newImage.save().then(() => {
           // console.log('added image to ' + folderName, public_id, name);
           res.status(201).json({ 'message': 'successfully added new Image', 'Image': newImage })
@@ -113,7 +113,7 @@ export const copyImagesForCategory = async (req, res) => {
 
   await Image.find({ categoryName: category, categoryId: oldId }, async function (err, foundImages) {
     if (err) {
-      console.log('error in find', err);
+      // console.log('error in find', err);
     } else {
       if (foundImages && foundImages.length > 0) {
         newImages = await Promise.all(foundImages.map(async (i) => {
@@ -153,7 +153,7 @@ export const deleteAllImagesFromCategory = async (req, res) => {
   // console.log('delete all images from ', category, id);
   await Image.find({ categoryName: category, categoryId: id }, async function (err, foundImages) {
     if (err) {
-      console.log('error in find', err);
+      // console.log('error in find', err);
     } else {
       await Promise.all(foundImages.map(async (i) => {
         await cloudinary.uploader.destroy(i.cloudinaryPublicId).catch(error => {

+ 3 - 3
server/controllers/users.controller.js

@@ -28,7 +28,7 @@ export const getAllUsers = async (req, res) => {
                  res.status(200).json(users);
                })
                .catch(function (err) {
-                 console.log('error when finding users', err);
+                 // console.log('error when finding users', err);
                  res.status(404).json({ message: err.message });
                });
 }
@@ -52,7 +52,7 @@ export const getUsersFromQuery = async (req, res) => {
                  res.status(200).json(users);
                })
                .catch(function (err) {
-                 console.log('error when finding users', err);
+                 // console.log('error when finding users', err);
                  res.status(404).json({ message: err.message });
                });
 }
@@ -65,7 +65,7 @@ export const getUserById = async (req, res) => {
                  res.status(200).json(user);
                })
                .catch(function (err) {
-                 console.log('error when finding user', err);
+                 // console.log('error when finding user', err);
                  res.status(404).json({ message: err.message });
                });