'Getting photo from array by path with firebase

I'm trying to show images from array by they path but getting error

App.js:44 Uncaught nc (in promise) TypeError: Cannot read properties of undefined (reading '_location')

I know that I must do something with promises, async functions etc., but I don't understand at all. So below is code example

const fireBaseApp = initializeApp(firebaseConfig);
const storage = getStorage(fireBaseApp);

function App() {
  const [url, setUrl] = useState([]);
  const [item, setItem] = useState([]);

  const listRef = ref(storage, "/");
  
  //getting all images from the bucket
  useEffect(() => {
    listAll(listRef).then((res) => {
      res.items.forEach(async (item) => {
        await setUrl((arr) => [...arr, item]);
      });
    });
  }, []);

  //Trying to download image from array with its' path
  useEffect(() => {
    const func = async () => {
      const download = ref(storage, url[2]._location.path_);
      await getDownloadURL(download).then((x) => {
        setItem(x);
      });
    };
    func();
  }, []);

  return (
    <>
      <img src={item} />
    </>
  );
}

So can anybody explain please how to do it properly. Thank you !



Solution 1:[1]

Add url[2] to the useEffect dependency array. But also check if it's set before running the async func. Like this:

useEffect(() => {
  if(url[2]){
    const func = async () => {
      const download = ref(storage, url[2]._location.path_);
      await getDownloadURL(download).then((x) => {
        setItem(x);
      });
     };
    func();
  }
}, [url[2]]);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CDoe