Jaaneek / useFilePicker

Simple react hook to open browser file selector.

Home Page:https://use-file-picker.vercel.app

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

onFileRemoved callback

dianeshan opened this issue · comments

Hi!
I have enjoyed using this file picker but ran into some issues with wanting to do things when a file is removed.
Would it be possible to add an onFileRemoved callback that allows us to specify what happens when we remove a file by index or by reference?

Thank you!

Hi @dianeshan,
There already is a function called onFileRemoved that is used in useImperativeFilePicker. However, I see now that I forgot to add it as a prop to the hook, so I'll add that in the next release.
If you're really on a clock and need this feature right now, you can hook to it by creating a custom validator and adding your logic there:
https://github.com/Jaaneek/useFilePicker#custom-validation
onFileRemoved is available since v2.0.

Example:

import { Validator } from "use-file-picker/validators";
import { useImperativeFilePicker } from "use-file-picker";

class OnFileRemovedCallback extends Validator {
  validateBeforeParsing(
    _config: UseFilePickerConfig<any>,
    _plainFiles: File[]
  ): Promise<void> {
    return Promise.resolve();
  }

  validateAfterParsing(
    _config: UseFilePickerConfig<any>,
    _file: FileWithPath,
    _reader: FileReader
  ): Promise<void> {
    return Promise.resolve();
  }

  onFileRemoved(removedIndex: number): void | Promise<void> {
    // add your logic here
  }
}

function App() {
 const {
    openFilePicker,
    errors,
    plainFiles,
    filesContent,
    removeFileByIndex,
  } = useImperativeFilePicker({
    validators: [
      new OnFileRemovedCallback(),
    ],
  });
  ...
}

There's currently no distinction if the file was removed by reference or by index, it always gets the index of a removed file in the files array. If you want, we can add a reference to the deleted file as a second argument.

Hi! Thank you so much for getting back to me so quickly! I do think adding a reference to the deleted file as a second argument would be good too.

Also do you have an estimate of when the next release will be?

I've just created a PR #80, I'm waiting for an approval from the co-author @Jaaneek. When he approves, I'll release a version 2.1.0. It shouldn't take long, like a few days at max.

PR has been quickly approved, I've just released version 2.1.0! I'm closing this issue for now, but feel free to comment.

Thank you very much! I think it would also actually be helpful to have another argument that is the result of filesContent when the file is removed. So we can do something with what is leftover after we remove a file.