1

useState() can't set file object. I added comments in the code to explain what's happening:

const [file, setFile] = useState<File>()
const onChange = async (
    imageList: ImageListType,
    addUpdateIndex: number[] | undefined
) => {
    if (imageList[0].file) {
        console.log("first image: ", imageList[0].file) // this line print out the right file object, but setFile NOT working below line
        setFile(imageList[0].file)
    }

    console.log("file: ", file) // this line will print undefined
}
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
hang
  • 133
  • 1
  • 1
  • 12

2 Answers2

1

When you call setFile(imageList[0].file), a re-render is need to have file updated. Updating a state is an asynchronous task, this why you are getting undefined. To see the updated value of file, you could add the console.log just after calling useState, this way:

const [file, setFile] = useState<File>()
console.log(file); // you will get undefined first, and after calling onChange the updated value

Or, you could use an useEffect, like so:

useEffect(()=>{
 if (file){
   console.log(file)
 }
},[file])
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
1

I do believe that useState can set any type of object however the problem here that you are setting the file then logging it which 90% work why is that? that's because ReactJs useState sets its state asynchronously

so in order to verify the file object add this to your code

useEffect(()=>{
   console.log(file)
},[file])
ZomitaKa
  • 475
  • 2
  • 7