KarimMokhtar / react-drag-drop-files

Light and simple Reactjs drag and drop files library to use with very flexible options to change, so you put whatever the design you want for your drop-area. Users can drag and drop or even select the file anywhere in the window.
MIT License
245 stars 86 forks source link

How to access and change internal state of files. #72

Open namansamra opened 2 years ago

namansamra commented 2 years ago

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.

Dakuan commented 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>
samos123 commented 2 years ago

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>

    );
}
marco-calderon commented 1 year ago

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.