Skip to content

Commit 3964ede

Browse files
committed
fix: update FilePreview to handle multiple renders in strict mode
1 parent da2849c commit 3964ede

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

src/components/forms/FileInput/FilePreview.test.tsx

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React from 'react'
1+
import React, { StrictMode } from 'react'
22
import { fireEvent, render, waitFor } from '@testing-library/react'
33

44
import { FilePreview } from './FilePreview'
@@ -27,6 +27,16 @@ describe('FilePreview component', () => {
2727
)
2828
})
2929

30+
it('renders without errors when loaded multiple times (simulating react dev mode)', () => {
31+
const { getByTestId } = render(
32+
<StrictMode>
33+
<FilePreview imageId="" file={TEST_TEXT_FILE} />
34+
</StrictMode>
35+
)
36+
37+
expect(getByTestId('file-input-preview')).toBeInTheDocument()
38+
})
39+
3040
it('renders a preview image', async () => {
3141
const { getByTestId } = await waitFor(() =>
3242
render(<FilePreview {...testProps} />)

src/components/forms/FileInput/FilePreview.tsx

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,23 @@ export const FilePreview = ({
1919
const [isLoading, setIsLoading] = useState(true)
2020
const [previewSrc, setPreviewSrc] = useState(SPACER_GIF)
2121
const [showGenericPreview, setShowGenericPreview] = useState(false)
22+
const firstRenderRef = useRef(false)
2223

2324
useEffect(() => {
25+
if (firstRenderRef.current) {
26+
// already run, do nothing
27+
return
28+
}
29+
// only run once
30+
firstRenderRef.current = true
31+
2432
fileReaderRef.current.onloadend = (): void => {
2533
setIsLoading(false)
2634
setPreviewSrc(fileReaderRef.current.result as string)
35+
fileReaderRef.current.onloadend = null // is only run once
2736
}
2837

2938
fileReaderRef.current.readAsDataURL(file)
30-
31-
return (): void => {
32-
fileReaderRef.current.onloadend = null
33-
}
3439
}, [])
3540

3641
const { name } = file

0 commit comments

Comments
 (0)