Skip to content

Fix svelte optimistic updates example#8005

Merged
manudeli merged 3 commits intoTanStack:mainfrom
BennettLiam:patch-1
Sep 3, 2025
Merged

Fix svelte optimistic updates example#8005
manudeli merged 3 commits intoTanStack:mainfrom
BennettLiam:patch-1

Conversation

@BennettLiam
Copy link
Contributor

@BennettLiam BennettLiam commented Sep 2, 2024

The example is currently broken. The random error on POST does not return and so items are always accepted.

Summary by CodeRabbit

  • Bug Fixes
    • Corrected POST error handling in the optimistic updates example API: on failure, the request now exits early, preventing unintended item creation and incorrect 200 responses.
    • Maintains existing successful flow; users now receive accurate error responses, improving demo reliability and predictability. Reduces confusing state mismatches between UI and server during failed submissions.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 3, 2025

Walkthrough

Introduces an early return in the POST error path of the Svelte route handler to stop execution after sending an error response. The success path is unchanged: create newTodo, push to items, and return 200 with the created item.

Changes

Cohort / File(s) Summary
API route POST control-flow fix
examples/svelte/optimistic-updates/src/routes/api/data/+server.ts
Added early return json(...) on POST failure to prevent continuing to create an item and sending a 200. Success path unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant S as Svelte Server (+server.ts)
  participant V as Validation/Lookup
  participant D as In-memory items

  C->>S: POST /api/data
  S->>V: Validate/lookup request data
  alt Error condition
    V-->>S: Error details
    S-->>C: json(error), status != 200
    note over S: Early return stops further execution
  else Success
    V-->>S: Validated payload
    S->>D: Create and push newTodo
    D-->>S: newTodo
    S-->>C: json(newTodo), status 200
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I nibble on code with a careful bite,
Snipping the path where errors take flight.
One early hop, no ghostly 200s bloom—
Now logic lands true, avoiding doom.
Thump-thump! The payload’s right,
A tidy burrow, responses light.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@nx-cloud
Copy link

nx-cloud bot commented Sep 3, 2025

View your CI Pipeline Execution ↗ for commit 178747d

Command Status Duration Result
nx affected --targets=test:sherif,test:knip,tes... ✅ Succeeded 56s View ↗
nx run-many --target=build --exclude=examples/*... ✅ Succeeded 1s View ↗

☁️ Nx Cloud last updated this comment at 2025-09-03 01:23:48 UTC

@pkg-pr-new
Copy link

pkg-pr-new bot commented Sep 3, 2025

More templates

@tanstack/angular-query-devtools-experimental

npm i https://pkg.pr.new/@tanstack/angular-query-devtools-experimental@8005

@tanstack/angular-query-experimental

npm i https://pkg.pr.new/@tanstack/angular-query-experimental@8005

@tanstack/eslint-plugin-query

npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@8005

@tanstack/query-async-storage-persister

npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@8005

@tanstack/query-broadcast-client-experimental

npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@8005

@tanstack/query-core

npm i https://pkg.pr.new/@tanstack/query-core@8005

@tanstack/query-devtools

npm i https://pkg.pr.new/@tanstack/query-devtools@8005

@tanstack/query-persist-client-core

npm i https://pkg.pr.new/@tanstack/query-persist-client-core@8005

@tanstack/query-sync-storage-persister

npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@8005

@tanstack/react-query

npm i https://pkg.pr.new/@tanstack/react-query@8005

@tanstack/react-query-devtools

npm i https://pkg.pr.new/@tanstack/react-query-devtools@8005

@tanstack/react-query-next-experimental

npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@8005

@tanstack/react-query-persist-client

npm i https://pkg.pr.new/@tanstack/react-query-persist-client@8005

@tanstack/solid-query

npm i https://pkg.pr.new/@tanstack/solid-query@8005

@tanstack/solid-query-devtools

npm i https://pkg.pr.new/@tanstack/solid-query-devtools@8005

@tanstack/solid-query-persist-client

npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@8005

@tanstack/svelte-query

npm i https://pkg.pr.new/@tanstack/svelte-query@8005

@tanstack/svelte-query-devtools

npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@8005

@tanstack/svelte-query-persist-client

npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@8005

@tanstack/vue-query

npm i https://pkg.pr.new/@tanstack/vue-query@8005

@tanstack/vue-query-devtools

npm i https://pkg.pr.new/@tanstack/vue-query-devtools@8005

commit: 178747d

Copy link
Contributor

@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: 1

🧹 Nitpick comments (4)
examples/svelte/optimistic-updates/src/routes/api/data/+server.ts (4)

19-23: Add minimal input validation to avoid runtime errors.

Guard against missing/non-string text and return 400 early.

-  const { text } = await request.json()
-
-  if (Math.random() > 0.7) {
-    return json({ message: 'Could not add item!' }, { status: 500 })
-  }
+  const body = (await request.json()) as Partial<Todo>
+  const text = body?.text
+  if (typeof text !== 'string' || !text.trim()) {
+    return json({ message: 'text must be a non-empty string' }, { status: 400 })
+  }
+
+  if (Math.random() > 0.7) {
+    return json({ message: 'Could not add item!' }, { status: 500 })
+  }

25-28: Prefer stable IDs over Math.random().

Use crypto UUIDs for uniqueness; drop the unnecessary cast once validated.

 import { json } from '@sveltejs/kit'
+import { randomUUID } from 'node:crypto'
   const newTodo = {
-    id: Math.random().toString(),
-    text: text.toUpperCase() as string,
+    id: randomUUID(),
+    text: text.toUpperCase(),
   }

30-30: Nit: use 201 for resource creation.

Not required for the example, but more RESTful.

-  return json(newTodo, { status: 200 })
+  return json(newTodo, { status: 201 })

11-12: Remove redundant JSDoc type annotations.

You already have TS types on the handlers; the JSDoc adds noise.

-/** @type {import('./$types').RequestHandler} */
 export const GET: RequestHandler = async (req) => {
-/** @type {import('./$types').RequestHandler} */
 export const POST: RequestHandler = async ({ request }) => {

Also applies to: 17-18

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 0a35234 and 178747d.

📒 Files selected for processing (1)
  • examples/svelte/optimistic-updates/src/routes/api/data/+server.ts (1 hunks)

Comment on lines 21 to 23
if (Math.random() > 0.7) {
json({ message: 'Could not add item!' }, { status: 500 })
return json({ message: 'Could not add item!' }, { status: 500 })
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Early return correctly stops success path — fix looks good.

This prevents accidental creation on simulated failures and aligns with the PR intent.

To ensure the client surfaces this error, verify the mutation code throws on non-2xx responses:


🏁 Script executed:

#!/bin/bash
# From repo root
# 1) Find calls that POST to this endpoint
rg -nP -C2 --type=ts '(fetch|POST).*?/api/data' examples/svelte/optimistic-updates || true

# 2) Check mutation logic throws on !res.ok or otherwise propagates HTTP 500
rg -nP -C3 --type=ts '(mutationFn|createMutation|useMutation).*' examples/svelte/optimistic-updates || true
rg -nP -C2 --type=ts '!res\.ok|throw\s+new\s+Error' examples/svelte/optimistic-updates || true

Length of output: 296


🏁 Script executed:

#!/bin/bash
# List all files under the example to locate relevant client code
ls -R examples/svelte/optimistic-updates/src/routes

echo "---- +page.svelte ----"
sed -n '1,200p' examples/svelte/optimistic-updates/src/routes/+page.svelte || true

echo "---- +page.ts ----"
sed -n '1,200p' examples/svelte/optimistic-updates/src/routes/+page.ts || true

echo "---- All .ts files under src/lib ----"
find examples/svelte/optimistic-updates/src/lib -type f -name '*.ts'

Length of output: 4014


Add non-2xx error handling in createTodo
The createTodo function currently calls res.json() regardless of HTTP status, so 500 responses won’t throw and the mutation’s onError won’t run. In examples/svelte/optimistic-updates/src/routes/+page.svelte, update createTodo to check res.ok and throw on failure, for example:

const createTodo = async (text: string): Promise<Todo> => {
  const res = await fetch(endpoint, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ text }),
  });
  if (!res.ok) {
    const { message } = await res.json();
    throw new Error(message);
  }
  return res.json();
}
🤖 Prompt for AI Agents
In examples/svelte/optimistic-updates/src/routes/+page.svelte around lines where
createTodo calls fetch (referenced by the server change at
src/routes/api/data/+server.ts lines 21-23), createTodo currently calls
res.json() unconditionally so 500 responses won't trigger onError; update
createTodo to check res.ok after the fetch, if not ok await res.json() to
extract the message and throw a new Error(message), otherwise return await
res.json() so non-2xx responses propagate as exceptions to the mutation's
onError handler.

@manudeli manudeli merged commit c75a994 into TanStack:main Sep 3, 2025
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants