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

useImperativeFilePicker returning error in conjunction with setState

brianaderer opened this issue · comments

Hi Guys,
Thanks for a very useful little utility! I am seeing one error with the useImperativeFilePicker. When I attempt to set a State in onFileRemoved from inside the same component as the file picker in order to pass its value back up to the parent, I'm getting this error in the console
next-dev.js:20 Warning: Cannot update a component (Form) while rendering a different component (Image). To locate the bad setState() call inside Image, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
It only happens when setState is called by onFileRemoved, it only happens on the first call, subsequent calls have no error, and everything works fine. Here is the full filePicker code:

const { removeFileByIndex, openFilePicker, filesContent, plainFiles ,loading, errors } = useImperativeFilePicker({ readAs: 'DataURL', accept: 'image/*', multiple: true, readFilesContent: true, onFilesSelected: ({ plainFiles, filesContent, errors }) => { // this callback is always called, even if there are errors console.log('onFilesSelected', plainFiles, filesContent, errors); }, onFilesRejected: ({ errors }) => { // this callback is called when there were validation errors console.log('onFilesRejected', errors); }, onFilesSuccessfullySelected: ({ plainFiles, filesContent }) => { // this callback is called when there were no validation errors console.log('onFilesSuccessfullySelected', plainFiles, filesContent); setState(filesContent); }, onFileRemoved: (removedFile, removedIndex) => { // this callback is called when a file is removed from the list of selected files const newFiles = filesContent.filter((_, i) => i !== removedIndex); setState(newFiles); }, validators: [ //new FileAmountLimitValidator({ max: 1 }), new FileTypeValidator(['jpg', 'png']), new FileSizeValidator({ maxFileSize: 1024 * 1024 /* 50 MB */ }), // new ImageDimensionsValidator({ // maxHeight: 900, // in pixels // maxWidth: 1600, // minHeight: 600, // minWidth: 768, // }), ], });

I read somewhere that this may be tied to newer react versions and no matter what I can't get it to go away. Also, if I try to use a useEffect() hook anywhere inside the component that has the filepicker I get a similar error but fatal.

Thanks!

Hi,
Can you show the code for the whole component, not just the useFilePicker part? I can't really help when I don't have a full context of what's going on around the hook call. Also, please format the code. It's hard to read when it's mashed together like that

We couldn't reproduce it & we didn't get an answer back, feel free to reopen this issue or create a new one if you encounter this once again