Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
React, state setter not updating the value

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
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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])
about 4 years ago · Juan Pablo Isaza Report

0

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])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!