0

I have an upload component that uploads an image to firebase. When that was successful I want to empty the file input and rerender the component however it seems I can't reset the state in order to trigger a rerender. I already read, that setting state to null doesn't work so I tried a dummy object but console log always gives me the previous file name.

I would be thankful for a rerender fix or for some general advice how to handle this better.

const onFileChange = (e) => {
    setFile(e.target.files[0]);
};

const onUpload = async () => {
    if (file) {
        // do something
        setFile({ file: "none" });
        console.log(file.name);
    }
};

return (
    <>
        <input type="file" onChange={onFileChange} />
        <button onClick={onUpload}>Upload image</button>
    </>
);
95faf8e76605e973
  • 13,643
  • 3
  • 24
  • 51
qwertz
  • 59
  • 4
  • Duplicate of [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Guy Incognito Aug 13 '20 at 06:27
  • Try like, ```setFile("none")``` instead of ```setFile({ file: "none" });``` .. – Maniraj Murugan Aug 13 '20 at 06:31
  • Tried that as well and it didn't work. Also it's not a timing issue because the component doesn't rerender after waiting a while – qwertz Aug 13 '20 at 06:33
  • You need to show a [mcve]. There's nothing wrong in the current code other than trying to log the state change too early. – Guy Incognito Aug 13 '20 at 06:37
  • it is reproducible. the issue, however, is not on the logs (which is sounding like an x y problem) but more on the resetting of the input field (trying to re-render). correct me if am wrong, however, OP – 95faf8e76605e973 Aug 13 '20 at 07:01

1 Answers1

0

One way of resetting the file input field in React is to set have a ref bound to it and set its value to an empty string as needed. A value prop is useless in a file input in React since it is uncontrolled so to force a re-render in this way is futile.

useEffect(()=>{
  if (file === "none"){
    this.fileInput.value = "";
  }
}, [file])

const onUpload = async () => {
  if (file) {
    // do something
    setFile("none");
  }
};

<input type="file" onChange={onFileChange} ref={(ref)=>{this.fileInput = ref}} />

CodeSandBox: https://codesandbox.io/s/boring-mirzakhani-7d16s?file=/src/App.js

95faf8e76605e973
  • 13,643
  • 3
  • 24
  • 51