0

I am initializing the locationImage array and imvalidFileState like this:-

const [attendeeWaitingTime, setAttendeeWaitingTime]     =   useState("");
const [defaultFetchTime, setDefaultFetchTime]           =   useState("");
const [locationImage, setLocationImage]                 =   useState([]);
const [invalidFileState, setInvalidFileState]           =   useState(true);

I have a file input object in the associated form:-

<Form.Item name={"uploaded_images"} label="Upload File">
   <Input type={"file"} multiple={'multiple'} placeholder={"Select Image"} onChange={(e) => changeFile(e)}/>
</Form.Item>

The definition of the changeFile function is like this:-

const changeFile = e => {
    const files = e.target.files;
    setInvalidFileState(files.length === 0);
    /**
     * Check for the file type
     */
    const regex = new RegExp('image-*')
    for(let i = 0; i < files.length; i++) {
        var file = files[i];
        if(!regex.test(file.type)) {
            setInvalidFileState(true);
            return;
        }
    }
    setLocationImage(files);
    setInvalidFileState(false);
    console.log("Files ALL OK", invalidFileState);
    console.log("Files", locationImage);
}

The function behaves a bit weirdly. When I am selecting any image for the first time, invalidFileState is displayed as true and the locationImage is displayed as empty. However, from second time onwards, the values are displayed properly.

enter image description here

How can I fix this?

Saswat
  • 12,320
  • 16
  • 77
  • 156

1 Answers1

0

useState hook is asynchronous, and will not be reflected immediately. to perform an action on state update, you need to use the useEffect hook.

pass changeFile as an argument to useEffect and

useEffect(() => {
  //your changeFile   function   
}, [locationImage]); / tells useEffect  to only trigger when locationImage changes
monim
  • 3,641
  • 2
  • 10
  • 25