<html lang="en">
<head></head>
<body>

<form id="mainForm" method="post" action="https://stackblitz.com/run" target="_self">
<input type="hidden" name="project[files][.gitignore]" value="node_modules
.DS_Store
dist
dist-ssr
*.local
">
<input type="hidden" name="project[files][README.md]" value="# TanStack Router - Deferred Data Example

An example demonstrating deferred data loading.

- [TanStack Router Docs](https://tanstack.com/router)

## Start a new project based on this example

To start a new project based on this example, run:

```sh
npx gitpick TanStack/router/tree/main/examples/react/deferred-data deferred-data
```

## Getting Started

Install dependencies:

```sh
pnpm install
```

Start the development server:

```sh
pnpm dev
```

## Build

Build for production:

```sh
pnpm build
```

## About This Example

This example demonstrates:

- Deferred data loading
- Progressive enhancement
- Streaming data
- Suspense boundaries
- Optimized loading states
">
<input type="hidden" name="project[files][index.html]" value="&lt;!doctype html&gt;
&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot; /&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;
    &lt;title&gt;Vite App&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id=&quot;app&quot;&gt;&lt;/div&gt;
    &lt;script type=&quot;module&quot; src=&quot;/src/main.tsx&quot;&gt;&lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;
">
<input type="hidden" name="project[files][package.json]" value="{&quot;name&quot;:&quot;tanstack-router-react-example-deferred-data&quot;,&quot;private&quot;:true,&quot;type&quot;:&quot;module&quot;,&quot;scripts&quot;:{&quot;dev&quot;:&quot;vite --port 3000&quot;,&quot;build&quot;:&quot;vite build &amp;&amp; tsc --noEmit&quot;,&quot;preview&quot;:&quot;vite preview&quot;,&quot;start&quot;:&quot;vite&quot;},&quot;dependencies&quot;:{&quot;@tailwindcss/vite&quot;:&quot;^4.2.2&quot;,&quot;@tanstack/react-router&quot;:&quot;https://pkg.pr.new/TanStack/router/@tanstack/react-router@1e68341&quot;,&quot;@tanstack/react-router-devtools&quot;:&quot;https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@1e68341&quot;,&quot;react&quot;:&quot;^19.0.0&quot;,&quot;react-dom&quot;:&quot;^19.0.0&quot;,&quot;redaxios&quot;:&quot;^0.5.1&quot;,&quot;tailwindcss&quot;:&quot;^4.2.2&quot;,&quot;zod&quot;:&quot;^3.24.2&quot;},&quot;devDependencies&quot;:{&quot;@types/react&quot;:&quot;^19.0.8&quot;,&quot;@types/react-dom&quot;:&quot;^19.0.3&quot;,&quot;@vitejs/plugin-react&quot;:&quot;^6.0.1&quot;,&quot;typescript&quot;:&quot;^6.0.2&quot;,&quot;vite&quot;:&quot;^8.0.0&quot;}}">
<input type="hidden" name="project[files][tsconfig.json]" value="{
  &quot;compilerOptions&quot;: {
    &quot;strict&quot;: true,
    &quot;esModuleInterop&quot;: true,
    &quot;jsx&quot;: &quot;react-jsx&quot;,
    &quot;lib&quot;: [&quot;DOM&quot;, &quot;DOM.Iterable&quot;, &quot;ES2022&quot;],
    &quot;skipLibCheck&quot;: true
  }
}
">
<input type="hidden" name="project[files][vite.config.js]" value="import { defineConfig } from &#39;vite&#39;
import react from &#39;@vitejs/plugin-react&#39;
import tailwindcss from &#39;@tailwindcss/vite&#39;

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [tailwindcss(), react()],
})
">
<input type="hidden" name="project[files][.devcontainer/devcontainer.json]" value="{
  &quot;image&quot;: &quot;mcr.microsoft.com/devcontainers/typescript-node:24&quot;
}
">
<input type="hidden" name="project[files][.vscode/settings.json]" value="{
  &quot;files.watcherExclude&quot;: {
    &quot;**/routeTree.gen.ts&quot;: true
  },
  &quot;search.exclude&quot;: {
    &quot;**/routeTree.gen.ts&quot;: true
  },
  &quot;files.readonlyInclude&quot;: {
    &quot;**/routeTree.gen.ts&quot;: true
  }
}
">
<input type="hidden" name="project[files][src/main.tsx]" value="import React from &#39;react&#39;
import ReactDOM from &#39;react-dom/client&#39;
import {
  Await,
  ErrorComponent,
  Link,
  MatchRoute,
  Outlet,
  RouterProvider,
  createRootRoute,
  createRoute,
  createRouter,
  defer,
} from &#39;@tanstack/react-router&#39;
import { TanStackRouterDevtools } from &#39;@tanstack/react-router-devtools&#39;
import axios from &#39;redaxios&#39;
import type { ErrorComponentProps } from &#39;@tanstack/react-router&#39;
import &#39;./styles.css&#39;

type PostType = {
  id: string
  title: string
  body: string
}

type CommentType = {
  id: string
  postId: string
  name: string
  email: string
  body: string
}

const fetchPosts = async () =&gt; {
  console.info(&#39;Fetching posts...&#39;)
  await new Promise((r) =&gt; setTimeout(r, 100))
  return axios
    .get&lt;Array&lt;PostType&gt;&gt;(&#39;https://jsonplaceholder.typicode.com/posts&#39;)
    .then((r) =&gt; r.data.slice(0, 10))
}

const fetchPost = async (postId: string) =&gt; {
  console.info(`Fetching post with id ${postId}...`)

  const commentsPromise = new Promise((r) =&gt; setTimeout(r, 2000))
    .then(() =&gt;
      axios.get&lt;Array&lt;CommentType&gt;&gt;(
        `https://jsonplaceholder.typicode.com/comments?postId=${postId}`,
      ),
    )
    .then((r) =&gt; r.data)

  const post = await new Promise((r) =&gt; setTimeout(r, 1000))
    .then(() =&gt;
      axios.get&lt;PostType&gt;(
        `https://jsonplaceholder.typicode.com/posts/${postId}`,
      ),
    )
    .catch((err) =&gt; {
      if (err.status === 404) {
        throw new NotFoundError(`Post with id &quot;${postId}&quot; not found!`)
      }
      throw err
    })
    .then((r) =&gt; r.data)

  return {
    post,
    commentsPromise: defer(commentsPromise),
  }
}

function Spinner({ show, wait }: { show?: boolean; wait?: `delay-${number}` }) {
  return (
    &lt;div
      className={`inline-block animate-spin px-3 transition ${
        (show ?? true)
          ? `opacity-100 duration-500 ${wait ?? &#39;delay-300&#39;}`
          : &#39;duration-500 opacity-0 delay-0&#39;
      }`}
    &gt;
      ⍥
    &lt;/div&gt;
  )
}

const rootRoute = createRootRoute({
  component: RootComponent,
})

function RootComponent() {
  return (
    &lt;&gt;
      &lt;div className=&quot;p-2 flex gap-2 text-lg&quot;&gt;
        &lt;Link
          to=&quot;/&quot;
          activeProps={{
            className: &#39;font-bold&#39;,
          }}
          activeOptions={{ exact: true }}
        &gt;
          Home
        &lt;/Link&gt;{&#39; &#39;}
        &lt;Link
          to=&quot;/posts&quot;
          activeProps={{
            className: &#39;font-bold&#39;,
          }}
        &gt;
          Posts
        &lt;/Link&gt;
      &lt;/div&gt;
      &lt;hr /&gt;
      &lt;Outlet /&gt;
      {/* Start rendering router matches */}
      &lt;TanStackRouterDevtools position=&quot;bottom-right&quot; /&gt;
    &lt;/&gt;
  )
}

const indexRoute = createRoute({
  getParentRoute: () =&gt; rootRoute,
  path: &#39;/&#39;,
}).update({
  component: IndexComponent,
})

function IndexComponent() {
  return (
    &lt;div className=&quot;p-2&quot;&gt;
      &lt;h3&gt;Welcome Home!&lt;/h3&gt;
    &lt;/div&gt;
  )
}

const postsRoute = createRoute({
  getParentRoute: () =&gt; rootRoute,
  path: &#39;posts&#39;,
  loader: fetchPosts,
  component: PostsComponent,
})

function PostsComponent() {
  const posts = postsRoute.useLoaderData()

  return (
    &lt;div className=&quot;p-2 flex gap-2&quot;&gt;
      &lt;ul className=&quot;list-disc pl-4&quot;&gt;
        {[...posts, { id: &#39;i-do-not-exist&#39;, title: &#39;Non-existent Post&#39; }].map(
          (post) =&gt; {
            return (
              &lt;li key={post.id} className=&quot;whitespace-nowrap&quot;&gt;
                &lt;Link
                  to={postRoute.to}
                  params={{
                    postId: post.id,
                  }}
                  className=&quot;flex py-1 text-blue-600 hover:opacity-75 gap-2 items-center&quot;
                  activeProps={{ className: &#39;font-bold underline&#39; }}
                &gt;
                  &lt;div&gt;{post.title.substring(0, 20)}&lt;/div&gt;
                  &lt;MatchRoute
                    to={postRoute.to}
                    params={{
                      postId: post.id,
                    }}
                    pending
                  &gt;
                    {(match) =&gt; {
                      return &lt;Spinner show={!!match} wait=&quot;delay-0&quot; /&gt;
                    }}
                  &lt;/MatchRoute&gt;
                &lt;/Link&gt;
              &lt;/li&gt;
            )
          },
        )}
      &lt;/ul&gt;
      &lt;hr /&gt;
      &lt;Outlet /&gt;
    &lt;/div&gt;
  )
}

class NotFoundError extends Error {}

const postRoute = createRoute({
  getParentRoute: () =&gt; postsRoute,
  path: &#39;$postId&#39;,
  loader: async ({ params: { postId } }) =&gt; fetchPost(postId),
  errorComponent: PostErrorComponent,
  component: PostComponent,
})

function PostErrorComponent({ error }: ErrorComponentProps) {
  if (error instanceof NotFoundError) {
    return &lt;div&gt;{error.message}&lt;/div&gt;
  }

  return &lt;ErrorComponent error={error} /&gt;
}

function PostComponent() {
  const { post, commentsPromise } = postRoute.useLoaderData()

  return (
    &lt;div className=&quot;space-y-2&quot;&gt;
      &lt;h4 className=&quot;text-xl font-bold underline&quot;&gt;{post.title}&lt;/h4&gt;
      &lt;div className=&quot;text-sm&quot;&gt;{post.body}&lt;/div&gt;
      &lt;React.Suspense
        fallback={
          &lt;div className=&quot;flex items-center gap-2&quot;&gt;
            &lt;Spinner /&gt;
            Loading comments...
          &lt;/div&gt;
        }
        key={post.id}
      &gt;
        &lt;Await promise={commentsPromise}&gt;
          {(comments) =&gt; {
            return (
              &lt;div className=&quot;space-y-2&quot;&gt;
                &lt;h5 className=&quot;text-lg font-bold underline&quot;&gt;Comments&lt;/h5&gt;
                {comments.map((comment) =&gt; {
                  return (
                    &lt;div key={comment.id}&gt;
                      &lt;h6 className=&quot;text-md font-bold&quot;&gt;{comment.name}&lt;/h6&gt;
                      &lt;div className=&quot;text-sm italic opacity-50&quot;&gt;
                        {comment.email}
                      &lt;/div&gt;
                      &lt;div className=&quot;text-sm&quot;&gt;{comment.body}&lt;/div&gt;
                    &lt;/div&gt;
                  )
                })}
              &lt;/div&gt;
            )
          }}
        &lt;/Await&gt;
      &lt;/React.Suspense&gt;
    &lt;/div&gt;
  )
}

const routeTree = rootRoute.addChildren([
  postsRoute.addChildren([postRoute]),
  indexRoute,
])

// Set up a Router instance
const router = createRouter({
  routeTree,
  defaultPreload: &#39;intent&#39;,
  scrollRestoration: true,
})

// Register things for typesafety
declare module &#39;@tanstack/react-router&#39; {
  interface Register {
    router: typeof router
  }
}

const rootElement = document.getElementById(&#39;app&#39;)!

if (!rootElement.innerHTML) {
  const root = ReactDOM.createRoot(rootElement)

  root.render(&lt;RouterProvider router={router} /&gt;)
}
">
<input type="hidden" name="project[files][src/styles.css]" value="@import &#39;tailwindcss&#39; source(&#39;../&#39;);

@layer base {
  *,
  ::after,
  ::before,
  ::backdrop,
  ::file-selector-button {
    border-color: var(--color-gray-200, currentcolor);
  }
}

html {
  color-scheme: light dark;
}
* {
  @apply border-gray-200 dark:border-gray-800;
}
body {
  @apply bg-gray-50 text-gray-950 dark:bg-gray-900 dark:text-gray-200;
}
">
<input type="hidden" name="project[files][src/vite-env.d.ts]" value="/// &lt;reference types=&quot;vite/client&quot; /&gt;
">
<input type="hidden" name="project[description]" value="generated by https://pkg.pr.new">
<input type="hidden" name="project[template]" value="node">
<input type="hidden" name="project[title]" value="tanstack-router-react-example-deferred-data">
</form>
<script>document.getElementById("mainForm").submit();</script>

</body></html>