examples/04-selective-ssr-data-only.tsx
examples/04-selective-ssr-data-only.tsxBrowse 13 files
444 tokens
1,798 bytes
Token encoding: o200k_base
Snapshot 8e164d2
← Back to SKILL.md
1// Selective SSR: the loader fetches the RSC on the server,2// but the route component renders on the client because it needs browser APIs.3 4import * as React from 'react'5import type { ReactNode } from 'react'6import { createFileRoute } from '@tanstack/react-router'7import { createServerFn } from '@tanstack/react-start'8import {9 CompositeComponent,10 createCompositeComponent,11} from '@tanstack/react-start/rsc'12 13// Replace with your own server-side data source14declare function getDashboardStats(): Promise<{15 series: Array<{ x: number; y: number }>16 totalUsers: number17}>18 19const getDashboard = createServerFn({ method: 'GET' }).handler(async () => {20 const stats = await getDashboardStats()21 22 const src = await createCompositeComponent<{23 renderChart?: (args: {24 series: Array<{ x: number; y: number }>25 }) => ReactNode26 }>((props) => (27 <section>28 <h1>Users: {stats.totalUsers}</h1>29 {props.renderChart?.({ series: stats.series })}30 </section>31 ))32 33 return { src }34})35 36export const Route = createFileRoute('/dashboard')({37 ssr: 'data-only',38 loader: async () => ({39 Dashboard: await getDashboard(),40 }),41 component: DashboardPage,42})43 44function DashboardPage() {45 const { Dashboard } = Route.useLoaderData()46 const [width, setWidth] = React.useState(0)47 48 React.useEffect(() => {49 setWidth(window.innerWidth)50 }, [])51 52 return (53 <CompositeComponent54 src={Dashboard.src}55 renderChart={({ series }) => (56 <ResponsiveChart data={series} width={width} />57 )}58 />59 )60}61 62// Replace with your real chart component63function ResponsiveChart(props: {64 data: Array<{ x: number; y: number }>65 width: number66}) {67 return (68 <pre>69 {JSON.stringify({ width: props.width, points: props.data.length })}70 </pre>71 )72}73