project: format all

This commit is contained in:
2025-09-25 14:38:58 +02:00
parent b8d64f325b
commit 7950e6761c
15 changed files with 134 additions and 144 deletions

View File

@@ -7,7 +7,5 @@
"git": true,
"version": 1,
"framework": "react-cra",
"chosenAddOns": [
"start"
]
}
"chosenAddOns": ["start"]
}

View File

@@ -1,4 +1,4 @@
Welcome to your new TanStack app!
Welcome to your new TanStack app!
# Getting Started
@@ -29,10 +29,8 @@ pnpm test
This project uses [Tailwind CSS](https://tailwindcss.com/) for styling.
## Routing
This project uses [TanStack Router](https://tanstack.com/router). The initial setup is a file based router. Which means that the routes are managed as files in `src/routes`.
### Adding A Route
@@ -48,13 +46,13 @@ Now that you have two routes you can use a `Link` component to navigate between
To use SPA (Single Page Application) navigation you will need to import the `Link` component from `@tanstack/react-router`.
```tsx
import { Link } from "@tanstack/react-router";
import { Link } from '@tanstack/react-router';
```
Then anywhere in your JSX you can use it like so:
```tsx
<Link to="/about">About</Link>
<Link to='/about'>About</Link>
```
This will create a link that will navigate to the `/about` route.
@@ -68,32 +66,31 @@ In the File Based Routing setup the layout is located in `src/routes/__root.tsx`
Here is an example layout that includes a header:
```tsx
import { Outlet, createRootRoute } from '@tanstack/react-router'
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
import { Outlet, createRootRoute } from '@tanstack/react-router';
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools';
import { Link } from "@tanstack/react-router";
import { Link } from '@tanstack/react-router';
export const Route = createRootRoute({
component: () => (
<>
<header>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to='/'>Home</Link>
<Link to='/about'>About</Link>
</nav>
</header>
<Outlet />
<TanStackRouterDevtools />
</>
),
})
});
```
The `<TanStackRouterDevtools />` component is not required so you can remove it if you don't want it in your layout.
More information on layouts can be found in the [Layouts documentation](https://tanstack.com/router/latest/docs/framework/react/guide/routing-concepts#layouts).
## Data Fetching
There are multiple ways to fetch data in your application. You can use TanStack Query to fetch data from a server. But you can also use the `loader` functionality built into TanStack Router to load the data for a route before it's rendered.
@@ -103,9 +100,9 @@ For example:
```tsx
const peopleRoute = createRoute({
getParentRoute: () => rootRoute,
path: "/people",
path: '/people',
loader: async () => {
const response = await fetch("https://swapi.dev/api/people");
const response = await fetch('https://swapi.dev/api/people');
return response.json() as Promise<{
results: {
name: string;
@@ -140,7 +137,7 @@ pnpm add @tanstack/react-query @tanstack/react-query-devtools
Next we'll need to create a query client and provider. We recommend putting those in `main.tsx`.
```tsx
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
// ...
@@ -154,7 +151,7 @@ if (!rootElement.innerHTML) {
root.render(
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
</QueryClientProvider>,
);
}
```
@@ -162,13 +159,13 @@ if (!rootElement.innerHTML) {
You can also add TanStack Query Devtools to the root route (optional).
```tsx
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
const rootRoute = createRootRoute({
component: () => (
<>
<Outlet />
<ReactQueryDevtools buttonPosition="top-right" />
<ReactQueryDevtools buttonPosition='top-right' />
<TanStackRouterDevtools />
</>
),
@@ -178,15 +175,15 @@ const rootRoute = createRootRoute({
Now you can use `useQuery` to fetch your data.
```tsx
import { useQuery } from "@tanstack/react-query";
import { useQuery } from '@tanstack/react-query';
import "./App.css";
import './App.css';
function App() {
const { data } = useQuery({
queryKey: ["people"],
queryKey: ['people'],
queryFn: () =>
fetch("https://swapi.dev/api/people")
fetch('https://swapi.dev/api/people')
.then((res) => res.json())
.then((data) => data.results as { name: string }[]),
initialData: [],
@@ -221,9 +218,9 @@ pnpm add @tanstack/store
Now let's create a simple counter in the `src/App.tsx` file as a demonstration.
```tsx
import { useStore } from "@tanstack/react-store";
import { Store } from "@tanstack/store";
import "./App.css";
import { useStore } from '@tanstack/react-store';
import { Store } from '@tanstack/store';
import './App.css';
const countStore = new Store(0);
@@ -231,9 +228,7 @@ function App() {
const count = useStore(countStore);
return (
<div>
<button onClick={() => countStore.setState((n) => n + 1)}>
Increment - {count}
</button>
<button onClick={() => countStore.setState((n) => n + 1)}>Increment - {count}</button>
</div>
);
}
@@ -246,9 +241,9 @@ One of the many nice features of TanStack Store is the ability to derive state f
Let's check this out by doubling the count using derived state.
```tsx
import { useStore } from "@tanstack/react-store";
import { Store, Derived } from "@tanstack/store";
import "./App.css";
import { useStore } from '@tanstack/react-store';
import { Store, Derived } from '@tanstack/store';
import './App.css';
const countStore = new Store(0);
@@ -264,9 +259,7 @@ function App() {
return (
<div>
<button onClick={() => countStore.setState((n) => n + 1)}>
Increment - {count}
</button>
<button onClick={() => countStore.setState((n) => n + 1)}>Increment - {count}</button>
<div>Doubled - {doubledCount}</div>
</div>
);

View File

@@ -39,4 +39,4 @@
"vitest": "^3.0.5",
"web-vitals": "^4.2.4"
}
}
}

View File

@@ -1 +1 @@
minimumReleaseAge: 4320 # 3 days
minimumReleaseAge: 4320 # 3 days

View File

@@ -25,4 +25,4 @@ const config = {
embeddedLanguageFormatting: 'auto',
};
export default config;
export default config;

View File

@@ -1,21 +1,21 @@
import { Link } from '@tanstack/react-router'
import { Link } from '@tanstack/react-router';
export default function Header() {
return (
<header className="p-2 flex gap-2 bg-white text-black justify-between">
<nav className="flex flex-row">
<div className="px-2 font-bold">
<Link to="/">Home</Link>
<header className='p-2 flex gap-2 bg-white text-black justify-between'>
<nav className='flex flex-row'>
<div className='px-2 font-bold'>
<Link to='/'>Home</Link>
</div>
<div className="px-2 font-bold">
<Link to="/demo/start/server-funcs">Start - Server Functions</Link>
<div className='px-2 font-bold'>
<Link to='/demo/start/server-funcs'>Start - Server Functions</Link>
</div>
<div className="px-2 font-bold">
<Link to="/demo/start/api-request">Start - API Request</Link>
<div className='px-2 font-bold'>
<Link to='/demo/start/api-request'>Start - API Request</Link>
</div>
</nav>
</header>
)
);
}

View File

@@ -1,7 +1,7 @@
import { createRouter } from '@tanstack/react-router'
import { createRouter } from '@tanstack/react-router';
// Import the generated route tree
import { routeTree } from './routeTree.gen'
import { routeTree } from './routeTree.gen';
// Create a new router instance
export const getRouter = () => {
@@ -9,5 +9,5 @@ export const getRouter = () => {
routeTree,
scrollRestoration: true,
defaultPreloadStaleTime: 0,
})
}
});
};

View File

@@ -1,10 +1,10 @@
import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router'
import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'
import { TanstackDevtools } from '@tanstack/react-devtools'
import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router';
import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools';
import { TanstackDevtools } from '@tanstack/react-devtools';
import Header from '../components/Header'
import Header from '../components/Header';
import appCss from '../styles.css?url'
import appCss from '../styles.css?url';
export const Route = createRootRoute({
head: () => ({
@@ -29,11 +29,11 @@ export const Route = createRootRoute({
}),
shellComponent: RootDocument,
})
});
function RootDocument({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<html lang='en'>
<head>
<HeadContent />
</head>
@@ -54,5 +54,5 @@ function RootDocument({ children }: { children: React.ReactNode }) {
<Scripts />
</body>
</html>
)
);
}

View File

@@ -1,4 +1,4 @@
import { createFileRoute } from '@tanstack/react-router'
import { createFileRoute } from '@tanstack/react-router';
export const Route = createFileRoute('/api/demo-names')({
server: {
@@ -8,8 +8,8 @@ export const Route = createFileRoute('/api/demo-names')({
headers: {
'Content-Type': 'application/json',
},
})
});
},
},
},
})
});

View File

@@ -1,44 +1,44 @@
import { useEffect, useState } from 'react'
import { useEffect, useState } from 'react';
import { createFileRoute } from '@tanstack/react-router'
import { createFileRoute } from '@tanstack/react-router';
function getNames() {
return fetch('/api/demo-names').then((res) => res.json())
return fetch('/api/demo-names').then((res) => res.json());
}
export const Route = createFileRoute('/demo/start/api-request')({
component: Home,
})
});
function Home() {
const [names, setNames] = useState<Array<string>>([])
const [names, setNames] = useState<Array<string>>([]);
useEffect(() => {
getNames().then(setNames)
}, [])
getNames().then(setNames);
}, []);
return (
<div
className="flex items-center justify-center min-h-screen p-4 text-white"
className='flex items-center justify-center min-h-screen p-4 text-white'
style={{
backgroundColor: '#000',
backgroundImage:
'radial-gradient(ellipse 60% 60% at 0% 100%, #444 0%, #222 60%, #000 100%)',
}}
>
<div className="w-full max-w-2xl p-8 rounded-xl backdrop-blur-md bg-black/50 shadow-xl border-8 border-black/10">
<h1 className="text-2xl mb-4">Start API Request Demo - Names List</h1>
<ul className="mb-4 space-y-2">
<div className='w-full max-w-2xl p-8 rounded-xl backdrop-blur-md bg-black/50 shadow-xl border-8 border-black/10'>
<h1 className='text-2xl mb-4'>Start API Request Demo - Names List</h1>
<ul className='mb-4 space-y-2'>
{names.map((name) => (
<li
key={name}
className="bg-white/10 border border-white/20 rounded-lg p-3 backdrop-blur-sm shadow-md"
className='bg-white/10 border border-white/20 rounded-lg p-3 backdrop-blur-sm shadow-md'
>
<span className="text-lg text-white">{name}</span>
<span className='text-lg text-white'>{name}</span>
</li>
))}
</ul>
</div>
</div>
)
);
}

View File

@@ -1,9 +1,9 @@
import fs from 'node:fs'
import { useCallback, useState } from 'react'
import { createFileRoute, useRouter } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/react-start'
import fs from 'node:fs';
import { useCallback, useState } from 'react';
import { createFileRoute, useRouter } from '@tanstack/react-router';
import { createServerFn } from '@tanstack/react-start';
const filePath = 'todos.json'
const filePath = 'todos.json';
async function readTodos() {
return JSON.parse(
@@ -17,81 +17,81 @@ async function readTodos() {
2,
),
),
)
);
}
const getTodos = createServerFn({
method: 'GET',
}).handler(async () => await readTodos())
}).handler(async () => await readTodos());
const addTodo = createServerFn({ method: 'POST' })
.inputValidator((d: string) => d)
.handler(async ({ data }) => {
const todos = await readTodos()
todos.push({ id: todos.length + 1, name: data })
await fs.promises.writeFile(filePath, JSON.stringify(todos, null, 2))
return todos
})
const todos = await readTodos();
todos.push({ id: todos.length + 1, name: data });
await fs.promises.writeFile(filePath, JSON.stringify(todos, null, 2));
return todos;
});
export const Route = createFileRoute('/demo/start/server-funcs')({
component: Home,
loader: async () => await getTodos(),
})
});
function Home() {
const router = useRouter()
let todos = Route.useLoaderData()
const router = useRouter();
let todos = Route.useLoaderData();
const [todo, setTodo] = useState('')
const [todo, setTodo] = useState('');
const submitTodo = useCallback(async () => {
todos = await addTodo({ data: todo })
setTodo('')
router.invalidate()
}, [addTodo, todo])
todos = await addTodo({ data: todo });
setTodo('');
router.invalidate();
}, [addTodo, todo]);
return (
<div
className="flex items-center justify-center min-h-screen bg-gradient-to-br from-zinc-800 to-black p-4 text-white"
className='flex items-center justify-center min-h-screen bg-gradient-to-br from-zinc-800 to-black p-4 text-white'
style={{
backgroundImage:
'radial-gradient(50% 50% at 20% 60%, #23272a 0%, #18181b 50%, #000000 100%)',
}}
>
<div className="w-full max-w-2xl p-8 rounded-xl backdrop-blur-md bg-black/50 shadow-xl border-8 border-black/10">
<h1 className="text-2xl mb-4">Start Server Functions - Todo Example</h1>
<ul className="mb-4 space-y-2">
<div className='w-full max-w-2xl p-8 rounded-xl backdrop-blur-md bg-black/50 shadow-xl border-8 border-black/10'>
<h1 className='text-2xl mb-4'>Start Server Functions - Todo Example</h1>
<ul className='mb-4 space-y-2'>
{todos?.map((t) => (
<li
key={t.id}
className="bg-white/10 border border-white/20 rounded-lg p-3 backdrop-blur-sm shadow-md"
className='bg-white/10 border border-white/20 rounded-lg p-3 backdrop-blur-sm shadow-md'
>
<span className="text-lg text-white">{t.name}</span>
<span className='text-lg text-white'>{t.name}</span>
</li>
))}
</ul>
<div className="flex flex-col gap-2">
<div className='flex flex-col gap-2'>
<input
type="text"
type='text'
value={todo}
onChange={(e) => setTodo(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
submitTodo()
submitTodo();
}
}}
placeholder="Enter a new todo..."
className="w-full px-4 py-3 rounded-lg border border-white/20 bg-white/10 backdrop-blur-sm text-white placeholder-white/60 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent"
placeholder='Enter a new todo...'
className='w-full px-4 py-3 rounded-lg border border-white/20 bg-white/10 backdrop-blur-sm text-white placeholder-white/60 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent'
/>
<button
disabled={todo.trim().length === 0}
onClick={submitTodo}
className="bg-blue-500 hover:bg-blue-600 disabled:bg-blue-500/50 disabled:cursor-not-allowed text-white font-bold py-3 px-4 rounded-lg transition-colors"
className='bg-blue-500 hover:bg-blue-600 disabled:bg-blue-500/50 disabled:cursor-not-allowed text-white font-bold py-3 px-4 rounded-lg transition-colors'
>
Add todo
</button>
</div>
</div>
</div>
)
);
}

View File

@@ -1,39 +1,39 @@
import { createFileRoute } from '@tanstack/react-router'
import logo from '../logo.svg'
import { createFileRoute } from '@tanstack/react-router';
import logo from '../logo.svg';
export const Route = createFileRoute('/')({
component: App,
})
});
function App() {
return (
<div className="text-center">
<header className="min-h-screen flex flex-col items-center justify-center bg-[#282c34] text-white text-[calc(10px+2vmin)]">
<div className='text-center'>
<header className='min-h-screen flex flex-col items-center justify-center bg-[#282c34] text-white text-[calc(10px+2vmin)]'>
<img
src={logo}
className="h-[40vmin] pointer-events-none animate-[spin_20s_linear_infinite]"
alt="logo"
className='h-[40vmin] pointer-events-none animate-[spin_20s_linear_infinite]'
alt='logo'
/>
<p>
Edit <code>src/routes/index.tsx</code> and save to reload.
</p>
<a
className="text-[#61dafb] hover:underline"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
className='text-[#61dafb] hover:underline'
href='https://reactjs.org'
target='_blank'
rel='noopener noreferrer'
>
Learn React
</a>
<a
className="text-[#61dafb] hover:underline"
href="https://tanstack.com"
target="_blank"
rel="noopener noreferrer"
className='text-[#61dafb] hover:underline'
href='https://tanstack.com'
target='_blank'
rel='noopener noreferrer'
>
Learn TanStack
</a>
</header>
</div>
)
);
}

View File

@@ -1,15 +1,14 @@
@import "tailwindcss";
@import 'tailwindcss';
body {
@apply m-0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
font-family:
-apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell',
'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
monospace;
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace;
}

View File

@@ -22,7 +22,7 @@
"noUncheckedSideEffectImports": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"@/*": ["./src/*"]
}
}
}

View File

@@ -1,8 +1,8 @@
import { defineConfig } from 'vite'
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import viteReact from '@vitejs/plugin-react'
import viteTsConfigPaths from 'vite-tsconfig-paths'
import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite';
import { tanstackStart } from '@tanstack/react-start/plugin/vite';
import viteReact from '@vitejs/plugin-react';
import viteTsConfigPaths from 'vite-tsconfig-paths';
import tailwindcss from '@tailwindcss/vite';
const config = defineConfig({
plugins: [
@@ -14,6 +14,6 @@ const config = defineConfig({
tanstackStart(),
viteReact(),
],
})
});
export default config
export default config;