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
}
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 undifined. 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 undifined first, and after calling onChange the updated value
Or, you could use an useEffect, like so:
useEffect(()=>{
if (file){
console.log(file)
}
},[file])
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])