Unverified Commit 70d98765 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[next/image] Only fire `onError` once (#93209)

parent a2fd4ea5
...@@ -3,12 +3,12 @@ ...@@ -3,12 +3,12 @@
import React, { import React, {
useRef, useRef,
useEffect, useEffect,
useCallback,
useContext, useContext,
useMemo, useMemo,
useState, useState,
forwardRef, forwardRef,
use, use,
useLayoutEffect,
} from 'react' } from 'react'
import ReactDOM from 'react-dom' import ReactDOM from 'react-dom'
import Head from '../shared/lib/head' import Head from '../shared/lib/head'
...@@ -44,7 +44,7 @@ export type { ImageLoaderProps } ...@@ -44,7 +44,7 @@ export type { ImageLoaderProps }
export type ImageLoader = (p: ImageLoaderProps) => string export type ImageLoader = (p: ImageLoaderProps) => string
type ImgElementWithDataProp = HTMLImageElement & { type ImgElementWithDataProp = HTMLImageElement & {
'data-loaded-src': string | undefined 'data-loaded-src'?: string | undefined
} }
type ImageElementProps = ImgProps & { type ImageElementProps = ImgProps & {
...@@ -180,6 +180,15 @@ function getDynamicProps( ...@@ -180,6 +180,15 @@ function getDynamicProps(
return { fetchpriority: fetchPriority } return { fetchpriority: fetchPriority }
} }
/**
* A version of useLayoutEffect that doesn't warn during SSR.
* TODO: Just useLayoutEffect once support for React 18 is dropped.
* Do not rename this to "isomorphic layout effect". There is no such thing as
* an isomorphic Layout Effect since there is no Layout on the server
*/
const useNonWarningLayoutEffect =
typeof window === 'undefined' ? useEffect : useLayoutEffect
const ImageElement = forwardRef<HTMLImageElement | null, ImageElementProps>( const ImageElement = forwardRef<HTMLImageElement | null, ImageElementProps>(
( (
{ {
...@@ -207,18 +216,25 @@ const ImageElement = forwardRef<HTMLImageElement | null, ImageElementProps>( ...@@ -207,18 +216,25 @@ const ImageElement = forwardRef<HTMLImageElement | null, ImageElementProps>(
}, },
forwardedRef forwardedRef
) => { ) => {
const ownRef = useCallback( const didInsertRef = useRef(false)
(img: ImgElementWithDataProp | null) => { const insertedImgRef = useRef<HTMLImageElement>(null)
if (!img) {
return useNonWarningLayoutEffect(() => {
} const { current: didInsert } = didInsertRef
const { current: img } = insertedImgRef
if (!didInsert && img !== null) {
// Replay events from during hydration that React doesn't replay.
if (onError) { if (onError) {
// If the image has an error before react hydrates, then the error is lost. // If the image has an error before react hydrates, then the error is lost.
// The workaround is to wait until the image is mounted which is after hydration, // The workaround is to wait until the image is mounted which is after hydration,
// then we set the src again to trigger the error handler (if there was an error). // then we set the src again to trigger the error handler (if there was an error).
// This doesn't just trigger the error handler but retries the whole request.
// TODO: Consider dispatching a synthetic event instead.
// eslint-disable-next-line no-self-assign // eslint-disable-next-line no-self-assign
img.src = img.src img.src = img.src
} }
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
if (!src) { if (!src) {
console.error(`Image is missing required "src" property:`, img) console.error(`Image is missing required "src" property:`, img)
...@@ -240,22 +256,24 @@ const ImageElement = forwardRef<HTMLImageElement | null, ImageElementProps>( ...@@ -240,22 +256,24 @@ const ImageElement = forwardRef<HTMLImageElement | null, ImageElementProps>(
sizesInput sizesInput
) )
} }
}, didInsertRef.current = true
[ }
src, }, [
placeholder, src,
onLoadRef, placeholder,
onLoadingCompleteRef, onLoadRef,
setBlurComplete, onLoadingCompleteRef,
onError, onError,
unoptimized, unoptimized,
sizesInput, sizesInput,
] ])
)
const ref = useMergedRef(forwardedRef, ownRef) const ref = useMergedRef(forwardedRef, insertedImgRef)
return ( return (
// If you move this element creation, also move the Layout Effect above
// reading from the ref. Otherwise we might run the Layout Effect when
// the current value isn't set to the HTMLImageElement instance.
<img <img
{...rest} {...rest}
{...getDynamicProps(fetchPriority)} {...getDynamicProps(fetchPriority)}
...@@ -280,9 +298,9 @@ const ImageElement = forwardRef<HTMLImageElement | null, ImageElementProps>( ...@@ -280,9 +298,9 @@ const ImageElement = forwardRef<HTMLImageElement | null, ImageElementProps>(
src={src} src={src}
ref={ref} ref={ref}
onLoad={(event) => { onLoad={(event) => {
const img = event.currentTarget as ImgElementWithDataProp const currentImage = event.currentTarget
handleLoading( handleLoading(
img, currentImage,
placeholder, placeholder,
onLoadRef, onLoadRef,
onLoadingCompleteRef, onLoadingCompleteRef,
......
'use client'
'use no memo'
import { useReducer, useState } from 'react'
import Image from 'next/image'
export default function Page() {
const [, setLoadEvent] = useState<unknown>(null)
const [showClientImage, setShowClientImage] = useState(false)
const [, rerender] = useReducer((i) => i + 1, 0)
return (
<>
<Image
alt="foo"
width={5}
height={5}
unoptimized
src="/test.png?hydrated"
onError={() => {}}
onLoad={(event) => {
console.error('hydrated image load')
// This doesn't really make sense. We just want to check rerendering
// doesn't infinitely loop
setLoadEvent(event)
}}
/>
<button type="button" onClick={rerender}>
rerender Page
</button>
<button type="button" onClick={() => setShowClientImage(true)}>
Show Client image
</button>
{showClientImage && (
<Image
alt="bar"
width={5}
height={5}
unoptimized
src="/test.png?client"
onError={() => {}}
onLoad={(event) => {
console.error('client rendered image load')
// This doesn't really make sense. We just want to check rerendering
// doesn't infinitely loop
setLoadEvent(event)
}}
/>
)}
</>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
'use no memo'
import { useReducer, useState } from 'react'
import Image from 'next/image'
export default function Page() {
const [, setErrorEvent] = useState<unknown>(null)
const [showClientImage, setShowClientImage] = useState(false)
const [, rerender] = useReducer((i) => i + 1, 0)
return (
<>
<Image
alt="foo"
width={5}
height={5}
unoptimized
src="/will-never-exist.png"
onError={(event) => {
console.error('hydrated image error')
// This doesn't really make sense. We just want to check rerendering
// doesn't infinitely loop
setErrorEvent(event)
}}
/>
<button type="button" onClick={rerender}>
rerender Page
</button>
<button type="button" onClick={() => setShowClientImage(true)}>
Show Client image
</button>
{showClientImage && (
<Image
alt="bar"
width={5}
height={5}
unoptimized
src="/still-doesnt-exist.png"
onError={(event) => {
console.error('client rendered image error')
// This doesn't really make sense. We just want to check rerendering
// doesn't infinitely loop
setErrorEvent(event)
}}
/>
)}
</>
)
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('next-image-events', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should not call onLoad multiple times', async () => {
const imageRequests = []
const browser = await next.browser('/fulfilled', {
beforePageLoad(page) {
page.on('request', (request) => {
if (request.resourceType() === 'image') {
imageRequests.push(request.url())
}
})
},
})
let logsIdx = 0
await retry(async () => {
const logs = await browser.log()
expect(
logs.slice(logsIdx).filter(({ source }) => source === 'error')
).toEqual([
{
source: 'error',
message: 'hydrated image load',
},
])
logsIdx = logs.length
})
expect(imageRequests).toEqual([expect.stringContaining('test')])
imageRequests.length = 0
await browser.locator(':text("Show Client image")').click()
await retry(async () => {
const logs = await browser.log()
expect(
logs.slice(logsIdx).filter(({ source }) => source === 'error')
).toEqual([
{
source: 'error',
message: 'client rendered image load',
},
])
logsIdx = logs.length
})
expect(imageRequests).toEqual([expect.stringContaining('test')])
imageRequests.length = 0
await browser.locator(':text("rerender Page")').click()
const logs = await browser.log()
expect(
logs.slice(logsIdx).filter(({ source }) => source === 'error')
).toEqual([])
expect(imageRequests).toEqual([])
imageRequests.length = 0
})
it('should not infinitely retry on error', async () => {
const nextImageRequests: string[] = []
let logsIdx = 0
const browser = await next.browser('/rejected', {
beforePageLoad(page) {
// We're manually aborting here to simulate an error before React hydrates.
// A real request might settle too late to test this behavior reliably.
// Especially in dev, requests (even if warm) may take longer than hydration.
page.route(
/\/will-never-exist\.png|\/still-doesnt-exist\.png/,
(route) => {
nextImageRequests.push(route.request().url())
return route.abort()
}
)
},
})
await retry(async () => {
const logs = await browser.log()
expect(
logs.slice(logsIdx).filter(({ source }) => source === 'error')
).toEqual([
{
source: 'error',
message: 'Failed to load resource: net::ERR_FAILED',
},
// Next.js retries once to trigger onError on SSRed, settled images.
// If this test fails, we'll either hydrated faster than the request settled,
// or dropped the retrying behavior of next/image
{
source: 'error',
message: 'Failed to load resource: net::ERR_FAILED',
},
{
source: 'error',
message: 'hydrated image error',
},
])
logsIdx = logs.length
})
expect(nextImageRequests).toEqual([
expect.stringContaining('will-never-exist'),
// Next.js retries once to trigger onError on SSRed, settled images.
// If this test fails, we'll either hydrated faster than the request settled,
// or dropped the retrying behavior of next/image
expect.stringContaining('will-never-exist'),
])
nextImageRequests.length = 0
await browser.locator(':text("Show Client image")').click()
await retry(async () => {
const logs = await browser.log()
expect(
logs.slice(logsIdx).filter(({ source }) => source === 'error')
).toEqual([
{
source: 'error',
message: 'Failed to load resource: net::ERR_FAILED',
},
{
source: 'error',
message: 'client rendered image error',
},
])
logsIdx = logs.length
})
expect(nextImageRequests).toEqual([
expect.stringContaining('still-doesnt-exist'),
])
nextImageRequests.length = 0
await browser.locator(':text("rerender Page")').click()
const logs = await browser.log()
expect(
logs.slice(logsIdx).filter(({ source }) => source === 'error')
).toEqual([])
expect(nextImageRequests).toEqual([])
nextImageRequests.length = 0
logsIdx = logs.length
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment