0

I'm quite new to react hooks, and I'm trying to update an array using useState([]) The following function should take files uploaded by the user, then I send it to the backend API which returns a unique ID for each inserted file. However, when I append each ID using the hook, the array always stays empty.

const uploadForm= () => {
     const [fileList, setFileList] = useState([]) 
     const [fileID, setFileID] = useState([])

     //insert code to set filepath

     for (const file of filepath[0]){
            const filename = file.name
            
            axios.post('/api/filesRoute/fs', { filename : filename })
            .then((json) => {
                console.log('Success uploading ', filename)
                console.log(json.data.id)
                setFileID( (prevfileID) => [...prevfileID, json.data.id])
            })

    console.log('file array: ', fileID)


}

This prints to console

printed to console

so if I upload 2 files, it should generate an ID for both, but the last console.log(fileID) is not being printed. Am I using useState([]) wrong? Any help would be appreciated!

Ruo
  • 77
  • 7
  • Your console logging `fileID` when the component is rendering, and that happens before your promise is resolved. If you want to console log the live value consider using `useEffect` and adding `fileID` as the dependency instead. – Terry May 29 '23 at 21:14

0 Answers0