snapshot of https://github.com/TanStack/query.git (main, 2026-09-16; blobs > 131072B omitted)
Some checks failed
autofix.ci / autofix (push) Failing after 4s
Release / Release (push) Has been skipped
GitHub Actions Security Analysis / Run zizmor (push) Failing after 2s

This commit is contained in:
upstream-mirror
2026-09-16 01:13:08 +05:00
commit 3a013ccdfe
3570 changed files with 490194 additions and 0 deletions

View File

@@ -0,0 +1,9 @@
.DS_Store
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
!lib/

View File

@@ -0,0 +1,38 @@
# create-svelte
Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/master/packages/create-svelte).
## Creating a project
If you're seeing this, you've probably already done this step. Congrats!
```bash
# create a new project in the current directory
npm create svelte@latest
# create a new project in my-app
npm create svelte@latest my-app
```
## Developing
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn` or `bun install`), start a development server:
```bash
npm run dev
# or start the server and open the app in a new browser tab
npm run dev -- --open
```
## Building
To create a production version of your app:
```bash
npm run build
```
You can preview the production build with `npm run preview`.
> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.

View File

@@ -0,0 +1,23 @@
{
"name": "@tanstack/query-example-svelte-optimistic-updates",
"private": true,
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"@tanstack/svelte-query": "^6.1.48",
"@tanstack/svelte-query-devtools": "^6.1.48"
},
"devDependencies": {
"@sveltejs/adapter-auto": "^6.1.0",
"@sveltejs/kit": "^2.57.1",
"@sveltejs/vite-plugin-svelte": "^5.1.1",
"svelte": "^5.39.3",
"svelte-check": "^4.3.1",
"typescript": "5.8.3",
"vite": "^6.4.1"
}
}

View File

@@ -0,0 +1,81 @@
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
.card {
padding: 2em;
}
main {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

View File

@@ -0,0 +1,12 @@
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface Platform {}
}
}
export {}

View File

@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

View File

@@ -0,0 +1,23 @@
<script lang="ts">
import '../app.css'
import { browser } from '$app/environment'
import { QueryClientProvider, QueryClient } from '@tanstack/svelte-query'
import { SvelteQueryDevtools } from '@tanstack/svelte-query-devtools'
const { children } = $props()
const queryClient = new QueryClient({
defaultOptions: {
queries: {
enabled: browser,
},
},
})
</script>
<QueryClientProvider client={queryClient}>
<main>
{@render children()}
</main>
<SvelteQueryDevtools />
</QueryClientProvider>

View File

@@ -0,0 +1,129 @@
<script lang="ts">
import '../app.css'
import {
useQueryClient,
createQuery,
createMutation,
} from '@tanstack/svelte-query'
type Todo = {
id: string
text: string
}
type Todos = {
items: readonly Todo[]
ts: number
}
let text = $state<string>('')
const client = useQueryClient()
const endpoint = '/api/data'
const fetchTodos = async (): Promise<Todos> =>
await fetch(endpoint).then((r) => r.json())
const createTodo = async (text: string): Promise<Todo> =>
await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text,
}),
}).then((res) => res.json())
const todos = createQuery<Todos>(() => ({
queryKey: ['optimistic'],
queryFn: fetchTodos,
}))
const addTodoMutation = createMutation(() => ({
mutationFn: createTodo,
onMutate: async (newTodo: string) => {
text = ''
// Cancel any outgoing refetches (so they don't overwrite our optimistic update)
await client.cancelQueries({ queryKey: ['optimistic'] })
// Snapshot the previous value
const previousTodos = client.getQueryData<Todos>(['optimistic'])
// Optimistically update to the new value
if (previousTodos) {
client.setQueryData<Todos>(['optimistic'], {
...previousTodos,
items: [
...previousTodos.items,
{ id: Math.random().toString(), text: newTodo },
],
})
}
return { previousTodos }
},
// If the mutation fails, use the context returned from onMutate to roll back
onError: (err: any, variables: any, context: any) => {
if (context?.previousTodos) {
client.setQueryData<Todos>(['optimistic'], context.previousTodos)
}
},
// Always refetch after error or success:
onSettled: () => {
client.invalidateQueries({ queryKey: ['optimistic'] })
},
}))
</script>
<h1>Optimistic Updates</h1>
<p>
In this example, new items can be created using a mutation. The new item will
be optimistically added to the list in hopes that the server accepts the item.
If it does, the list is refetched with the true items from the list. Every now
and then, the mutation may fail though. When that happens, the previous list
of items is restored and the list is again refetched from the server.
</p>
<form
onsubmit={(e) => {
e.preventDefault()
e.stopPropagation()
addTodoMutation.mutate(text)
}}
>
<div>
<input type="text" bind:value={text} />
<button disabled={addTodoMutation.isPending}>Create</button>
</div>
</form>
{#if todos.isPending}
Loading...
{/if}
{#if todos.error}
An error has occurred:
{todos.error.message}
{/if}
{#if todos.isSuccess}
<div class="mb-4">
Updated At: {new Date(todos.data.ts).toLocaleTimeString()}
</div>
<ul>
{#each todos.data.items as todo}
<li>{todo.text}</li>
{/each}
</ul>
{/if}
{#if todos.isFetching}
<div style="color:darkgreen; font-weight:700">
'Background Updating...' : ' '
</div>
{/if}
<style>
li {
text-align: left;
}
</style>

View File

@@ -0,0 +1,31 @@
import { json } from '@sveltejs/kit'
import type { RequestHandler } from '@sveltejs/kit'
type Todo = {
id: string
text: string
}
const items: Array<Todo> = []
/** @type {import('./$types').RequestHandler} */
export const GET: RequestHandler = async (req) => {
await new Promise((r) => setTimeout(r, 1000))
return json({ ts: Date.now(), items }, { status: 200 })
}
/** @type {import('./$types').RequestHandler} */
export const POST: RequestHandler = async ({ request }) => {
const { text } = await request.json()
if (Math.random() > 0.7) {
return json({ message: 'Could not add item!' }, { status: 500 })
}
const newTodo = {
id: Math.random().toString(),
text: text.toUpperCase() as string,
}
items.push(newTodo)
return json(newTodo, { status: 200 })
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,15 @@
import adapter from '@sveltejs/adapter-auto'
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'
/** @type {import('@sveltejs/kit').Config} */
const config = {
preprocess: vitePreprocess(),
kit: {
adapter: adapter(),
},
compilerOptions: {
runes: true,
},
}
export default config

View File

@@ -0,0 +1,17 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true
}
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

View File

@@ -0,0 +1,6 @@
import { sveltekit } from '@sveltejs/kit/vite'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [sveltekit()],
})