Problem
I’m on working with React on Chrome, and to upload a file I use <input type="file" />
. However, the first upload never works, but the subsequent uploads have absolutely no problems.
Edit: When I talk about the upload, I’m referring to the value of my useState pictureFile
, which is always false
when I first send a picture file. I’m really sorry for not being clear…
Trials
To tell you the truth, I really don’t know where to begin to deal with this problem…
I first tried to delete the onClick
, which is used to deal with the upload of the same file. But it has no effects. And I also tried some solutions found in an old Stack Overflow post but there are still no results.
Code
Below it’s my code:
import { useState } from "react";
function Settings() {
let [pictureFile, setPictureFile] = useState(false);
const updateAvatar = (event) => {
if (event.target.files && event.target.files.length > 0) {
setPictureFile(event.target.files[0]);
}
console.log(pictureFile);
};
return (
<div id="settingsContainer">
<input
type="file"
accept=".png, .jpeg, .jpg, .gif"
name="user_pictureURL"
id="user_pictureURL"
onChange={updateAvatar}
onClick={event => event.target.value = null}
/>
</div>
);
}
export default Settings;
I thank in advance anyone who will take the time to help me :D.
2
Answers
Do you want to see preview of your image? Or Just send it to the server?
set preview image :
Send it to the server
More details :
This is because the changes using useState will not reflect in the current context, the next time it works because it shows the previous context (the previously uploaded file) if you observe carefully while uploading different files.
This is common behaviour of useState, for more information go to the link