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