Skip to content

[fix] FilePreview component breaks FileReader use in onChange events #2433

@patsier-cms

Description

@patsier-cms

ReactUSWDS Version & USWDS Version:

@trussworks/react-uswds: 4.2.1
@uswds/uswds: 3.1.0

Describe the bug

When a function that uses FileReader is called from an onChange event in the FileInput component, it throws an error because FileReader is already being used on any added files in the FilePreview component.

Ideally, users should be able to disable calling FileReader inside the FilePreview component so that it can still be used in change events.

To Reproduce
Steps to reproduce the behavior:

  1. On Chrome, create a component using FileInput with an onChange event using FileReader
  2. Add a file
  3. See error Uncaught DOMException: Failed to execute 'readAsDataURL' on 'FileReader': The object is already busy reading Blobs.

Expected behavior

Using FileReader within the FileInput component should be optional

Additional context

My specific use case for this is to be able to validate text file input in onChange events, and I'd be happy to put in a PR that allows for disabling calling the FileReader which seems to only be used for generating image previews. Thanks for taking a look!

useEffect(() => {
fileReaderRef.current.onloadend = (): void => {
setIsLoading(false)
setPreviewSrc(fileReaderRef.current.result as string)
}
fileReaderRef.current.readAsDataURL(file)
return (): void => {
fileReaderRef.current.onloadend = null
}
}, [])

Device and Browser Information (please complete the following information if describing a UI bug):

  • Browser Chrome
  • Version 113.0.5672.126
  • Also reproduced on Firefox

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: bugSomething isn't working like it's supposed to

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions