Retaining selected image state on closePopup in React component

33 views Asked by At

I'm encountering an issue with a React component where I'm implementing functionality to upload images. When the user selects an image using the file input, the selected image is displayed within a popup. However, when the user clicks on the closePopup button, the selected image is cleared, preventing it from being saved to the backend.

  const openPopup = () => {
    setIsPopupOpen(true);
  };

  const closePopup = () => {
    setIsPopupOpen(false);
  };

const handleImageChange = (e, index) => {
    const file = e.target.files[0];
    if (file) {
      const imageUrl = URL.createObjectURL(file);
      setImages(`img${index}`, imageUrl);
    }
  };

     <button
        className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
        onClick={openPopup}
      >
        Open Popup
      </button>

      {isPopupOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center overflow-auto bg-gray-800 bg-opacity-75">
          <div className="bg-white rounded-lg p-8">
            <h2 className="text-xl font-semibold mb-4">Upload Image</h2>
            <input
              type="file"
              id="img2"
              className="block w-full border-gray-400 p-2 rounded"
              accept="image/*"
              onChange={handleImageChange}
            />
            <button
              className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
              onClick={closePopup}
            >
              Close
            </button>
          </div>
        </div>

i want when user click on closepop still selected image should present there so that it saved at MongoDB else as of now when i click on close popup it clear the field and that image not saving on mongodb

1

There are 1 answers

4
Booster On

To enable the storage of images in the database, it is imperative to develop a corresponding handler. This involves invoking an API upon modal closure to facilitate the seamless storage of the image in the database. Additionally, should retrieval of the image be necessary, the implementation of a corresponding GET API is essential.

An alternative approach involves utilizing the localStorage feature to temporarily store the image. This provides an efficient and practical solution for managing images within the system.