Skip to content

fix(nuxt): ensure newKey asyncData runs when oldKey asyncData is still running #32466

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Jun 26, 2025

Conversation

OrbisK
Copy link
Collaborator

@OrbisK OrbisK commented Jun 24, 2025

🔗 Linked issue

fixes #32109

📚 Description

This PR should fix #32109. It ensures that the newKey asyncdata is not only executed once the request for the old key has finished.

I'll still mark it as a draft so that I can check whether there is a better solution.

TODO: add tests

Note

It was not possible for me to reproduce this test as runtime or fixtures test. Only with full e2e test.

Copy link

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

Copy link

pkg-pr-new bot commented Jun 24, 2025

Open in StackBlitz

@nuxt/kit

npm i https://pkg.pr.new/@nuxt/kit@32466

nuxt

npm i https://pkg.pr.new/nuxt@32466

@nuxt/rspack-builder

npm i https://pkg.pr.new/@nuxt/rspack-builder@32466

@nuxt/schema

npm i https://pkg.pr.new/@nuxt/schema@32466

@nuxt/vite-builder

npm i https://pkg.pr.new/@nuxt/vite-builder@32466

@nuxt/webpack-builder

npm i https://pkg.pr.new/@nuxt/webpack-builder@32466

commit: f8354c2

@OrbisK
Copy link
Collaborator Author

OrbisK commented Jun 24, 2025

Maybe this should be solved here instead:

watch(key, setImmediate, { flush: 'sync', once: true })
watch([...watchSources || [], _fetchOptions], setImmediate, { flush: 'sync', once: true })

Copy link

codspeed-hq bot commented Jun 24, 2025

CodSpeed Performance Report

Merging #32466 will not alter performance

Comparing OrbisK:fix/async-data-while-running (f8354c2) with main (7bbddea)

Summary

✅ 10 untouched benchmarks

@OrbisK
Copy link
Collaborator Author

OrbisK commented Jun 24, 2025

Alternatively, setting experimental.alwaysRunFetchOnKeyChange to true does solve the issue too.

EDIT: now I wonder if this was intended https://nuxt.com/docs/4.x/api/nuxt-config#alwaysrunfetchonkeychange

@OrbisK OrbisK changed the title fix(asyncData): ensure newKey asyncData runs when oldKey asyncData is still running fix(nuxt): ensure newKey asyncData runs when oldKey asyncData is still running Jun 25, 2025
@OrbisK OrbisK marked this pull request as ready for review June 25, 2025 17:28
@Copilot Copilot AI review requested due to automatic review settings June 25, 2025 17:28
@OrbisK OrbisK requested a review from danielroe as a code owner June 25, 2025 17:28
Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR ensures that when changing asyncData keys, a new fetch is triggered even if the previous key’s asyncData call is still pending, fixing issue #32109.

  • Introduces an isRunning flag to detect ongoing asyncData promises and include it in the execution condition
  • Adds an API fixture (/api/wait/:ms) and a new E2E test for the useFetch composable with immediate: false
  • Updates related test fixtures and pages to verify parallel fetch execution

Reviewed Changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
test/fixtures/basic/server/api/wait/[ms].get.ts Adds a /api/wait/:ms endpoint fixture
test/fixtures/basic/app/pages/composables/fetch-immediate-false.vue Implements a page using useFetch with immediate: false
test/e2e/composables.test.ts E2E test for parallel fetch execution
packages/nuxt/src/app/composables/asyncData.ts Core change: include isRunning in asyncData watcher
Comments suppressed due to low confidence (2)

test/e2e/composables.test.ts:7

  • [nitpick] The comment describes testing the runtime compiler, but this suite is focused on the useFetch composable behavior; please update the description to match its actual purpose.
 * This test suite verifies that Vue's runtime compiler works correctly within Nuxt,

test/fixtures/basic/server/api/wait/[ms].get.ts:6

  • The message uses 'hey' which is inconsistent with the endpoint name '/wait'; consider renaming it to something like Hello from wait after ${ms}ms for clarity.
        message: `Hello from hey after ${ms}ms`,

@@ -327,6 +327,7 @@ export function useAsyncData<
const unsubExecute = watch([key, ...(options.watch || [])], ([newKey], [oldKey]) => {
if ((newKey || oldKey) && newKey !== oldKey) {
const hasRun = nuxtApp._asyncData[oldKey]?.data.value !== undefined
const isRunning = nuxtApp._asyncDataPromises[oldKey] !== undefined
Copy link
Preview

Copilot AI Jun 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add unit tests (e.g., using Vitest) for the new key-change logic in useAsyncData to cover cases where isRunning is true, as required by our core functionality testing guidelines.

Copilot uses AI. Check for mistakes.

Copy link

coderabbitai bot commented Jun 25, 2025

Walkthrough

A modification was made to the client-side watcher in the useAsyncData composable by introducing an isRunning boolean to track ongoing data fetches for the previous key. The logic for triggering a new fetch was updated to include cases where a fetch for the previous key is still running, alongside existing conditions. Additionally, a new test was added to the useFetch suite to verify handling of parallel executions when the immediate option is set to false. This test uses a reactive query and asserts correct status transitions through multiple reactive changes. No changes were made to exported or public entity declarations.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 766b3df and f8354c2.

📒 Files selected for processing (1)
  • test/nuxt/composables.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/nuxt/composables.test.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: codeql (javascript-typescript)
  • GitHub Check: build
  • GitHub Check: code
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in Comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
test/fixtures/basic/server/api/wait/[ms].get.ts (1)

1-10: LGTM! Consider adding type safety for the ms parameter.

The API route implementation is correct and serves its purpose for testing delayed responses. The graceful handling of invalid ms parameters is good.

Consider adding type validation for the parameter:

export default defineEventHandler((event) => {
  const ms = getRouterParam(event, 'ms')
+ const delay = ms ? Math.max(0, parseInt(ms, 10)) || 0 : 0
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
-       message: `Hello from hey after ${ms}ms`,
+       message: `Hello from hey after ${delay}ms`,
      })
-   }, ms ? +ms : 0)
+   }, delay)
  })
})
test/fixtures/basic/app/pages/composables/fetch-immediate-false.vue (1)

12-24: LGTM! Well-structured test component that follows Vue best practices.

The component correctly uses the Composition API with <script setup> and properly tests the fetch behavior with immediate: false. The watcher configuration with { once: true } effectively simulates the scenario where a key change should trigger a new fetch.

Consider adding a small delay to better simulate real-world timing scenarios:

-watch(query, () => execute(), { once: true })
+watch(query, () => nextTick(() => execute()), { once: true })
test/e2e/composables.test.ts (1)

34-44: Comprehensive e2e test that validates the fix effectively.

The test properly validates the new behavior where fetch execution is triggered on key changes even when the previous fetch might still be running. The step-by-step assertions cover the complete lifecycle from idle to success state.

Consider making the test name more descriptive of the specific scenario being tested:

-test('should handle parallel fetch execute with immediate: false and `experimental.alwaysRunFetchOnKeyChange: false`', async ({ page, goto }) => {
+test('should trigger new fetch on key change when previous fetch is still running with immediate: false', async ({ page, goto }) => {

The test logic is solid with appropriate assertions for status transitions and error handling.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2dafcc7 and 37d92ce.

📒 Files selected for processing (4)
  • packages/nuxt/src/app/composables/asyncData.ts (2 hunks)
  • test/e2e/composables.test.ts (1 hunks)
  • test/fixtures/basic/app/pages/composables/fetch-immediate-false.vue (1 hunks)
  • test/fixtures/basic/server/api/wait/[ms].get.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`**/*.ts`: Follow standard TypeScript conventions and best practices

**/*.ts: Follow standard TypeScript conventions and best practices

📄 Source: CodeRabbit Inference Engine (.github/copilot-instructions.md)

List of files the instruction was applied to:

  • test/fixtures/basic/server/api/wait/[ms].get.ts
  • packages/nuxt/src/app/composables/asyncData.ts
  • test/e2e/composables.test.ts
`**/*.vue`: Use <script setup lang="ts"> and the composition API when creating Vue components

**/*.vue: Use <script setup lang="ts"> and the composition API when creating Vue components

📄 Source: CodeRabbit Inference Engine (.github/copilot-instructions.md)

List of files the instruction was applied to:

  • test/fixtures/basic/app/pages/composables/fetch-immediate-false.vue
⏰ Context from checks skipped due to timeout of 90000ms (20)
  • GitHub Check: test-fixtures (windows-latest, built, webpack, default, manifest-on, json, 20)
  • GitHub Check: test-fixtures (windows-latest, built, webpack, async, manifest-on, json, 20)
  • GitHub Check: test-fixtures (windows-latest, built, rspack, default, manifest-on, json, 20)
  • GitHub Check: test-fixtures (windows-latest, built, vite, default, manifest-off, json, 20)
  • GitHub Check: test-fixtures (windows-latest, dev, vite, default, manifest-on, json, 20)
  • GitHub Check: test-fixtures (windows-latest, built, vite, async, manifest-on, json, 20)
  • GitHub Check: test-fixtures (windows-latest, dev, vite, async, manifest-on, json, 20)
  • GitHub Check: test-fixtures (windows-latest, dev, vite, default, manifest-off, json, 20)
  • GitHub Check: test-fixtures (windows-latest, built, vite, async, manifest-off, json, 20)
  • GitHub Check: test-fixtures (ubuntu-latest, built, vite, async, manifest-on, js, 20)
  • GitHub Check: test-fixtures (windows-latest, dev, vite, async, manifest-off, json, 20)
  • GitHub Check: test-fixtures (ubuntu-latest, built, webpack, default, manifest-on, json, 20)
  • GitHub Check: test-fixtures (ubuntu-latest, built, vite, async, manifest-on, json, 20)
  • GitHub Check: test-fixtures (ubuntu-latest, built, webpack, async, manifest-on, json, 20)
  • GitHub Check: test-fixtures (ubuntu-latest, dev, vite, async, manifest-on, js, 20)
  • GitHub Check: test-fixtures (ubuntu-latest, built, vite, async, manifest-off, json, 20)
  • GitHub Check: test-fixtures (ubuntu-latest, dev, vite, async, manifest-on, json, 20)
  • GitHub Check: test-fixtures (ubuntu-latest, dev, vite, default, manifest-off, json, 20)
  • GitHub Check: test-fixtures (ubuntu-latest, dev, vite, default, manifest-on, json, 20)
  • GitHub Check: test-benchmark
🔇 Additional comments (2)
packages/nuxt/src/app/composables/asyncData.ts (2)

330-330: Excellent addition to track running state.

This line correctly identifies when the old key has an ongoing async operation by checking for an existing promise in _asyncDataPromises.


341-341: Perfect fix for the blocking asyncData issue.

This change ensures that a new fetch is triggered not only when immediate is true or when the previous key's data has already run (hasRun), but also when there's still an ongoing fetch for the old key (isRunning). This resolves the core issue where newKey asyncData was blocked by ongoing oldKey operations.

The logic is sound and maintains backward compatibility whilst improving responsiveness.

import { fileURLToPath } from 'node:url'
import { isWindows } from 'std-env'
import { join } from 'pathe'
import { expect, test } from './test-utils'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there any chance we can use a nuxt runtime test rather than an e2e test?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@OrbisK you should be able to do it by mocking _asyncPromises. I can try to do it if you want

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@huang-julien that would be nice

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@huang-julien I have it! 💚

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

great 🔥 !

@OrbisK OrbisK force-pushed the fix/async-data-while-running branch from f1b70c1 to cf6a159 Compare June 26, 2025 13:09
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
test/nuxt/composables.test.ts (1)

927-927: Consider consistency in conditional test execution.

The conditional logic uses skipIf(process.env.NUXT_LEGACY !== '1') whilst other legacy tests in this file use runIf(process.env.PROJECT === 'nuxt-legacy'). This inconsistency could lead to confusion about when tests execute.

Consider using the same pattern for consistency:

-  it.skipIf(process.env.NUXT_LEGACY !== '1')('should handle parallel execute with `immediate: false`', async () => {
+  it.runIf(process.env.NUXT_LEGACY === '1')('should handle parallel execute with `immediate: false`', async () => {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f1b70c1 and cf6a159.

📒 Files selected for processing (2)
  • packages/nuxt/src/app/composables/asyncData.ts (2 hunks)
  • test/nuxt/composables.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/nuxt/src/app/composables/asyncData.ts
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.ts`: Follow standard TypeScript conventions and best practices

**/*.ts: Follow standard TypeScript conventions and best practices

📄 Source: CodeRabbit Inference Engine (.github/copilot-instructions.md)

List of files the instruction was applied to:

  • test/nuxt/composables.test.ts
🧠 Learnings (2)
📓 Common learnings
Learnt from: Tofandel
PR: nuxt/nuxt#0
File: :0-0
Timestamp: 2024-11-11T12:34:22.648Z
Learning: Ensure that AI-generated summaries accurately reflect the key changes in the PR, focusing on notable changes such as the removal of unused imports and variables starting with underscores.
Learnt from: huang-julien
PR: nuxt/nuxt#29366
File: packages/nuxt/src/app/components/nuxt-root.vue:16-19
Timestamp: 2024-12-12T12:36:34.871Z
Learning: In `packages/nuxt/src/app/components/nuxt-root.vue`, when optimizing bundle size by conditionally importing components based on route metadata, prefer using inline conditional imports like:

```js
const IsolatedPage = route?.meta?.isolate ? defineAsyncComponent(() => import('#build/isolated-page.mjs')) : null
```

instead of wrapping the import in a computed property or importing the component unconditionally.
test/nuxt/composables.test.ts (1)
Learnt from: CR
PR: nuxt/nuxt#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-06-23T19:10:10.027Z
Learning: Write end-to-end tests using Playwright and @nuxt/test-utils to validate application behavior from the user's perspective.
🔇 Additional comments (1)
test/nuxt/composables.test.ts (1)

928-951: Excellent test implementation for parallel execution behaviour.

This test effectively validates the core issue addressed in the PR - ensuring that useFetch with immediate: false properly handles parallel executions triggered by reactive changes. The test structure is sound:

  • Uses reactive objects to simulate real-world scenarios
  • Properly validates status transitions from 'idle' → 'pending' → 'success' → 'pending'
  • Employs vi.waitFor for reliable async state validation
  • Uses expect.soft for better debugging when assertions fail

The test logic correctly simulates the scenario where multiple rapid changes to reactive dependencies should trigger new fetches even when previous ones are still running.

Copy link
Member

@danielroe danielroe left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thank you ❤

@danielroe danielroe merged commit d680c3f into nuxt:main Jun 26, 2025
81 of 83 checks passed
@github-actions github-actions bot mentioned this pull request Jun 26, 2025
@github-actions github-actions bot mentioned this pull request Jul 1, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

useFetch with immediate: false causes watch to stop triggering in Nuxt 3.17.3
3 participants
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy