David Ho
David Ho

Reputation: 287

(Reactjs) How to submit the file immediately after selected the file

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.

Upvotes: 0

Views: 82

Answers (1)

Okan Karadag
Okan Karadag

Reputation: 3045

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])
}

Upvotes: 1

Related Questions