Removing data from firestore/storage does not follow the expected pathway

I have created an image gallery for users using Firebase Storage and React, allowing them to upload and delete images. However, I am facing an issue where the deletion process is taking longer than expected.

Expected flow:

User clicks on the trashcan icon > confirmation modal pops up > user confirms deletion > confirmation disappears and deletion process occurs.

Actual flow:

User clicks on the trashcan icon > confirmation modal pops up > user confirms deletion > confirmation disappears > user clicks on the trashcan icon again > deletion process occurs but another confirmation modal pops up.

export default function EditImageGallery({ handleUser }) {
  // code here
}

I would appreciate any insights on what may be causing this delay in the deletion process within my code. Feel free to ask for additional code if needed for further investigation.

Answer №1

Upon further investigation, I came to a realization. Following the setHidden(false) action, the subsequent execution of the if statement causes a change in the state of continueDelete. However, since the if statement is already evaluated at that point, it does not reevaluate the condition.

To address this issue, I opted to employ the use of useEffect for evaluation and deletion purposes.

useEffect(() => {
    const deleteData = async () => {
      const deleteRef = ref(storage, id);
      console.log("Proceeding with the deletion process:", deleteRef);
      await deleteObject(deleteRef)
        .then(() => {
          console.log("Item successfully deleted from Firebase Storage", deleteRef);
        })
        .catch((error) => {
          console.log(error.message);
          toast.error(error.message);
        });

      //delete reference in firestore
      try {
        const imageDelete = collection(db, "images");
        const q = query(imageDelete, where("imageURL", "==", id));
        const snaps = await getDocs(q);
        console.log("Number of documents to be deleted:", snaps.docs.length);
        snaps.docs.forEach(async (doc) => {
          console.log("Deleted Document: ", doc.ref.id);
          await deleteDoc(doc.ref);
          console.log("Deleted Document: ", doc.ref.id);
        });
        // await Promise.all(deletePromises);
        console.log("All documents have been deleted");
        window.location.reload(true);
      } catch (error) {
        console.log(error.message);
        setContinueDelete(false);
      }

      setContinueDelete(false);
    };

    if (continueDelete === true) {
      deleteData();
    }

    return () => {
      console.log("cleanup");
    };
  }, [continueDelete, id]);

  //Deletion process
  const onDelete = async (e) => {
    const { id } = e.target;
    console.log("Clicked URL", id);
    setId(id);
    setHidden(false);
  };
      

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize jQuery and HTML simplistically to display or conceal divs throughout a webpage

After developing some basic jQuery code using if-statements to toggle the visibility of Divs based on a select list in HTML, I am seeking ways to enhance this code: 1) How can I achieve the same functionality with fewer lines of code? 2) Rather than manu ...

React - Refreshing a component with the help of another component

I've created a NavBar component that contains a list of links generated dynamically. These links are fetched from the backend based on specific categories and are stored within a child component of NavBar named DrawerMenu. The NavBar itself is a chil ...

Preact was implemented within the Shadow DOM, but unfortunately, all of the styles were

Currently in the process of constructing a widget, I aim to load the Preact app for the widget within the shadow DOM to prevent any conflicts with CSS. Gratefully, I have achieved this successfully using the following technique: const host = document.que ...

Generate a text box that only accepts numbers

I'm in the process of creating a numeric-only input field using VueJS. It's mostly functioning correctly, but there is an issue that needs to be addressed: SUCCESS: Inputting 12 into the text field results in both the VueJS value and visual dis ...

Maintain the visibility of the jQuery dropdown menu even when navigating to a different page within the

I am experiencing an issue with my dropdown menu. Whenever I click on a "dropdown link", it opens another page on my website, but the menu closes in the process. I want to ensure that the menu stays open and highlights the clicked "dropdown link" in bold. ...

Vue.js - encountering an issue with undefined response data

Greetings! I've encountered a script issue while trying to submit a form in VUE. The error message displayed in the developer panel states: "TypeError: error.response.data.errors is undefined". As a newcomer to Vue, I'm seeking some assistance as ...

Is there a way to monitor individual users in the application based on their session, allowing for unique sets of redirects or rules for each user?

I am currently developing a URL shortener similar to Bitly, with all functionalities on a single page. The page includes a form where users can input the URL they want to shorten and a section displaying all abbreviated URLs associated with that user (with ...

Preserving scroll position during page navigation in Next.js

Currently, I am working on a website using the Next.js boilerplate. Here is the routing code that I am using: import Link from 'next/link' <Link href={{ pathname: '/some-url', query: { param: something } }}> <div> ...

While utilizing Ajax with Spring, it is possible to send a JavaScript object and receive it as a custom object. However, there was an issue with

One of my challenges in Java is working with a custom class that looks like this: public class AddressesVO { private Long addressId; private String address; public Long getAddressId() { return addressId; } public void setAddressId(Long addressId ...

Discover the basics of incorporating libraries using npm

As a beginner in JavaScript, I am looking to incorporate moment.js or another library into my project. However, I am unsure of how to properly set up my project so that I can import from the library. Here is how I have structured my HTML: <!DOCTYPE html ...

Click to remove the accordion div

My query is regarding an accordion feature that I have implemented. <div id="accordion" class="accord"> <h2> <a href="#">Item1</a></h2> <div> Content1 </div> <h2 > &l ...

Implementing popup alert for multiple tabs when Javascript session times out

I have implemented javascript setInterval() to monitor user idle time and display a popup alert prior to automatic logout. However, it seems to be functioning correctly only in single tabs. Here is the code snippet: localStorage.removeItem("idleTimeValue ...

Transforming a JSON file into a new JSON file using an alternative method in React

I have a JSON data structure similar to this example: [ { "quantity": "200", "prodType": "stock", "symbol": "LOL", "prodDesc": "Εθνική τράπεζα", "market": "Greece", "averageCost": "131,16", ...

Utilizing Firebase for Microsoft authentication

Currently, I am working on integrating Microsoft authentication with Firebase for a web project built in Vue.js 2. I have meticulously followed the steps outlined in the Firebase documentation and also referred to the Azure portal documentation for creatin ...

Jenkins is unable to locate the module, '@babel/plugin-proposal-private-property-in-object' (0:undefined) for React

An Error in Jenkins identified within the console.log terminal 13:29:56 A Syntax error has occurred: [BABEL] /var/jenkins_home/workspace/govt-finance/qa/build-and-deploy-web/node-app/src/index.js: Unable to locate module '@babel/plugin-proposal-priva ...

What methods can be used to center a Google map on a specific location?

I am facing an issue with three map canvases on different divs. Despite setting the center to the same position in all three of them using JavaScript, the second and third maps do not seem to reflect that center. Does anyone have any insights on what cou ...

Secure your browsing experience with AngularJS authentication prompt

Currently, I am working on building an application using AngularJS for the front-end and JavaEE for the back-end. In my AngularJS application, I am trying to access a REST resource provided by the back-end which is protected with JAAS authentication, allow ...

Is there a method to retrieve Mui state classes easily?

One thing I really appreciate is the way to style mui-components with their class names. I'm curious if there's a method to access state classes like Mui-checked using a variable. Let me delve deeper into this: I have a styled component that lo ...

Move information from one webpage to a different page

After developing a site using NextJs, I successfully integrated Discord login functionality and was able to retrieve the user's guilds in the oauth file. Now, I am looking to send this list of guilds (in JSON format) to my dashboard page. In the oau ...

View is unable to trigger the success attribute

Currently, I am delving deep into Backbone JS and facing an issue where the 'success' function in 'EditUser' is not being triggered. I would greatly appreciate it if someone could guide me on what changes I need to make in the code? B ...