Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

index.tsx

44 lines1019 Bytes

1import * as fs from 'node:fs'
2import { useRouter, createFileRoute } from '@tanstack/react-router'
3import { createServerFn } from '@tanstack/react-start'
4​
5const filePath = 'count.txt'
6​
7async function readCount() {
8 return parseInt(
9 await fs.promises.readFile(filePath, 'utf-8').catch(() => '0'),
10 )
12​
13const getCount = createServerFn({ method: 'GET' }).handler(() => {
14 return readCount()
15})
16​
17const updateCount = createServerFn({ method: 'POST' })
18 .inputValidator((addBy: number) => addBy)
19 .handler(async ({ data }) => {
20 const count = await readCount()
21 await fs.promises.writeFile(filePath, `${count + data}`)
22 })
23​
24export const Route = createFileRoute('/')({
25 component: Home,
26 loader: async () => await getCount(),
27})
28​
29function Home() {
30 const router = useRouter()
31 const state = Route.useLoaderData()
32​
33 return (
34 <button
35 onClick={() => {
36 updateCount({ data: 1 }).then(() => {
37 router.invalidate()
38 })
39 }}
40 >
41 Add 1 to {state}?
42 </button>
43 )