I am trying to submit an image using input field without a submit button. When the file is selected, it will be submitted automatically. I am thinking doing it like this:
const [image, setImage] = useState(null);
const updateState = (e) => {
setImage(e.target.files[0]);
}
const submitFile = async () => {
...submit the file...
}
<input accept='image/*' type='file' onChange={() => { updateState(); submitFile(); }} />
I really want to know is there a better way to do this? Because I not feeling right about this, it seems not very programmatic.
CodePudding user response:
you should use useEffect
for updated state
useEffect(() => {
if(image){
submitFile()
}
},[image])
<input accept='image/*' type='file' onChange={() => updateState()} />
or you can call it in update state
const updateState = (e) => {
setImage(e.target.files[0]);
submitFile(e.target.files[0])
}