Open namansamra opened 2 years ago
we worked around this by updating a key, thereby forcing a re-mount:
export const DragNDropPhoto = ({
onSelectFile,
disabled,
height,
}: Props): JSX.Element => {
const key = useRef(0);
const handleChange = useCallback(
(file) => {
onSelectFile(file);
key.current = key.current + 1;
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);
return (
<FileUploader
key={key.current}
handleChange={handleChange}
name="file"
>
{...component}
</FileUploader>
The workaround by @Dakuan works great. I implemented the workaround like this:
export default function UploadButton() {
const [key, setKey] = useState(1);
const [file, setFile] = useState(null);
const handleChange = (file) => {
setFile(file);
apiUpload(formData)
.then((response) => {
setImage(response);
setLoading("");
})
.catch((error) => {
console.log(error);
let errorMsg = error.message;
setError(errorMsg);
setLoading("");
setKey(key + 1);
});
};
return (
<FileUploader
handleChange={handleChange}
key={key}
classes="mt-3 pb-3"
name="file"
types={fileTypes}
>
<Button variant="primary" size="lg">
<Upload /> Upload
</Button>{" "}
<br />
or drop file here
</FileUploader>
);
}
While the solution above works I believe it would be better if we have this feature implemented. In some cases like working with lots of files can be tedious but for use cases of selecting a single file is enough though.
Problem: When I upload three files and remove them one by one, by setting the files[i]=null. Then if I again upload the same files it doesn't trigger the handleChange function. I assume that since the internal state of files still has the same names of the files thus it is not changing the state of these files.