skip to Main Content

I am creating a file upload using react. I want to set the state variable to the uploaded file(.docx or .pdf) as soon as the it was uploaded. But when the set state calls, it shows undefined.

   const [selectedFile, setSelectedFile] = useState(null)

   <Input type="file" onChange={handleImageUpload} accept={config.type}/>
   
   const handleImageUpload = (event: { target: { files: any[] } }) => {
        const file = event.target.files[0]
        if (file) {
        if (file.size > config?.fileSize) {
          setErrorMessage(config.fileSizeError)
        } else if (file?.name.endsWith(config.type)) {
          setSelectedFile(file)
        } else {
          reader.readAsDataURL(file)
        }
      }
   }

As soon as the setSelectedFile(file) happens, it shows selectedFile is undefined. Is there a specific reason why this is happening ?

3

Answers


  1. I think, your code works as expected, but it’s just your state hasn’t get updated when you tried to call it.

    From the react official docs:

    the set function only updates the state variable for the next render.
    If you read the state variable after calling the set function, you will 
    still get the old value that was on the screen before your call.
    

    Now, this is my speculation, but you can try to add this code:

    setSelectedFile(file)
    
    setTimeout(() => {
        console.log(selectedFile); 
    }, 5000);
    
    Login or Signup to reply.
  2. I tried to change event type to be a Partial instance of ChangeEvent:

    const handleImageUpload = (event: Partial<ChangeEvent<HTMLInputElement>>)
    

    and also changed onChange to accept the change event and pass it to handleImageUpload

    <input
            type="file"
            onChange={(event) => handleImageUpload(event)}
            accept={config.type}
          />
    

    It works properly and you can view selectedFile using a useEffect hook.

    Login or Signup to reply.
  3. This is happening because your state hasn’t updated when you called or logged it in the console. You can log your state in a useEffect hook to see it when it updates. Here’s an example;

      useEffect(() => {
        console.log("File >> ", selectedFile);
      }, [selectedFile]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search