Open History to see the last commit
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 )
11}
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 )
44}