Skip to content

Commit

Permalink
fix: Match SSR state, then fix after hydration
Browse files Browse the repository at this point in the history
As discussed in review, keep initial state in sync with SSR for first render. At hydration `isHydrated` will trigger another render call to update the image to the correct one if different due to art direction usage.

Rephrased comments, extracted shared logic from fluid/fixed conditionals (DRY). Doing so fails a test on null image data, so now additionally guard against that early.
  • Loading branch information
polarathene committed Sep 12, 2020
1 parent 121573d commit a06a07b
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions packages/gatsby-image/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -448,9 +448,9 @@ class Image extends React.Component {
draggable,
} = convertProps(this.props)

// Avoid render logic on client until component mounts (hydration complete)
// Prevents using mismatched initial state from the hydration phase
if (isBrowser && !this.state.isHydrated) {
const imageVariants = fluid || fixed
// Abort early if missing image data (#25371)
if (!imageVariants) {
return null
}

Expand Down Expand Up @@ -485,10 +485,14 @@ class Image extends React.Component {
itemProp,
}

if (fluid) {
const imageVariants = fluid
const image = getCurrentSrcData(fluid)
// Initial client render state needs to match SSR until hydration finishes.
// Once hydration completes, render again to update to the correct image.
// `imageVariants` is always an Array type at this point due to `convertProps()`
const image = !this.state.isHydrated
? imageVariants[0]
: getCurrentSrcData(imageVariants)

if (fluid) {
return (
<Tag
className={`${className ? className : ``} gatsby-image-wrapper`}
Expand Down Expand Up @@ -594,9 +598,6 @@ class Image extends React.Component {
}

if (fixed) {
const imageVariants = fixed
const image = getCurrentSrcData(fixed)

const divStyle = {
position: `relative`,
overflow: `hidden`,
Expand Down

0 comments on commit a06a07b

Please sign in to comment.