0

so I am trying to get into react but it gives me a lot of headaches... The current one: I created a State Hook which seems to be the react-version of a classical array.

    const [downloadLinks, setDownloadLinks] = useState([]);

Then I used an async function to fetch data:

    const getFileList = async() =>{
    const fileList = await list(
        listRef, {maxResults: 10}
        )
        .then(
            (res) => {
                res.items.forEach((item) => {
                    // We get the download link for each
                    getDownloadURL(ref(storage, item))
                    .then((url) => {
                        // log this link
                        console.log("getFileList-URL: " + url)
                        // Add it to the array
                        setDownloadLinks(old => [...old, url])
                        console.log("Test the length: " + downloadLinks.length)
                    })
                });
                getFileDescriptions();
            }
        );
    };

And here we see the issue: I looked up several ways to append elements to a state in react but it all comes down to this. And the state doesnt change at all. The length stays the same, there are no more elements inside. I even log "url" to be sure that it is not null. But nothing works.

Any advice?

Frank van Puffelen
  • 499,950
  • 69
  • 739
  • 734
Gauerdia
  • 35
  • 4
  • 2
    Your code looks fine, it's just that you have your console.log statement in a spot where it's useless. `setDownloadLinks` is not going to change the value in the local const `downloadLinks`, so your log statement is necessarily going to log out the old value. calling `setDownloadLinks` just asks that the component be rerendered. If you want to verify that the rerender happens, then move your log statement into the body of the component, say on the line right after `const [downloadLinks, setDownloadLinks] = useState([])` – Nicholas Tower Jan 02 '22 at 13:37

0 Answers0