From d72cfa7cad758192163712ceb269405659fd14bc Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Tue, 6 Jun 2023 17:39:25 +0800 Subject: [PATCH] Fix nested astro-island hydration race condition (#7197) --- .changeset/light-sheep-hunt.md | 5 +++++ packages/astro/src/runtime/server/astro-island.ts | 11 ++++++++--- scripts/cmd/prebuild.js | 1 + 3 files changed, 14 insertions(+), 3 deletions(-) create mode 100644 .changeset/light-sheep-hunt.md diff --git a/.changeset/light-sheep-hunt.md b/.changeset/light-sheep-hunt.md new file mode 100644 index 000000000..a32ab2d44 --- /dev/null +++ b/.changeset/light-sheep-hunt.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fix nested astro-island hydration race condition diff --git a/packages/astro/src/runtime/server/astro-island.ts b/packages/astro/src/runtime/server/astro-island.ts index 60db5b6b1..b24e6c0be 100644 --- a/packages/astro/src/runtime/server/astro-island.ts +++ b/packages/astro/src/runtime/server/astro-island.ts @@ -53,7 +53,8 @@ declare const Astro: { // Wait with a mutation observer new MutationObserver((_, mo) => { mo.disconnect(); - this.childrenConnectedCallback(); + // Wait until the next macrotask to ensure children are really rendered + setTimeout(() => this.childrenConnectedCallback(), 0); }).observe(this, { childList: true }); } } @@ -98,7 +99,11 @@ declare const Astro: { hydrate = () => { if ( !this.hydrator || - (this.parentElement && this.parentElement.closest('astro-island[ssr]')) + // Make sure the island is mounted on the DOM before hydrating. It could be unmounted + // when the parent island hydrates and re-creates this island. + !this.isConnected || + // Wait for parent island to hydrate first so we hydrate top-down. + this.parentElement?.closest('astro-island[ssr]') ) { return; } @@ -129,7 +134,7 @@ declare const Astro: { window.dispatchEvent(new CustomEvent('astro:hydrate')); }; attributeChangedCallback() { - if (this.hydrator) this.hydrate(); + this.hydrate(); } } ); diff --git a/scripts/cmd/prebuild.js b/scripts/cmd/prebuild.js index 99208a29f..305298f72 100644 --- a/scripts/cmd/prebuild.js +++ b/scripts/cmd/prebuild.js @@ -69,6 +69,7 @@ export default async function prebuild(...args) { sourcefile: filepath, }, format: 'iife', + target: ['es2018'], minify, bundle: true, write: false,