Image Stay After Refreshed Firebase

I am using firebase with react to store images that the user can upload but when I refresh the page. The image gets removed, how do I keep the image?


  const [image, setImage] = useState(null);
  const [url, setUrl] = useState("");
  const [progress, setProgress] = useState(0);

  const handleChange = e => {
    if (e.target.files[0]) {
      setImage(e.target.files[0]);
    }
  };

  const handleUpload = () => {
    const uploadTask = storage.ref(`images/${image.name}`).put(image);
    uploadTask.on(
      "state_changed",
      snapshot => {
        const progress = Math.round(
          (snapshot.bytesTransferred / snapshot.totalBytes) * 100
        );
        setProgress(progress);
      },
      error => {
        console.log(error);
      },
      () => {
        storage
          .ref("images")
          .child(image.name)
          .getDownloadURL()
          .then(url => {
            setUrl(url);
          });
      }
    );
  };
   
  return (
    <div className='App'>
    <Header/>
    <br />
    <br />
    {progress > 0 && progress < 100 ?
    <progress value={progress} max="100" /> : <div></div>
    }
    <div class="proPic">
    <Avatar src={url} sx={{ width: 250, height: 250 }} />
    <input type="file" onChange={handleChange} />
    <button onClick={handleUpload}>Submit</button>
    </div>
    </div>
  )
}

Would I have to add another storage to keep the image?

I am still confused as how to save the image upload.

I think the answer is going to involve useEffect but I am not sure how to get the most recent uploaded image url to use.

//this code refreshes the image but randomly selects one from my firebase account
const imagesListRef = ref(storage, "images/");

  useEffect(() => {
    list(imagesListRef).then((response) => {
      response.items.forEach((item) => {
        getDownloadURL(item).then((url) => {
          setUrl(url);
          console.log(url);
        });
      });
    });
  }, []);

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.