Open History to see the last commit
1import { Outlet, createFileRoute } from '@tanstack/solid-router'
2import z from 'zod'
3import { ssrSchema } from '~/search'
4β
5export const Route = createFileRoute('/posts')({
6 validateSearch: z.object({ posts: ssrSchema }),
7 ssr: ({ search }) => {
8 if (typeof window !== 'undefined') {
9 const error = `ssr() for ${Route.id} should not be called on the client`
10 console.error(error)
11 throw new Error(error)
12 }
13 if (search.status === 'success') {
14 return search.value.posts?.ssr
15 }
16 },
17 beforeLoad: ({ search }) => {
18 if (typeof window !== 'undefined') {
19 if (Route.options.ssr !== undefined) {
20 const error = `ssr() for ${Route.id} should have been deleted from the Route options on the client`
21 console.error(error)
22 throw new Error(error)
23 }
24 }
25 console.log(
26 `beforeLoad for ${Route.id} called on the ${typeof window !== 'undefined' ? 'client' : 'server'}`,
27 )
28 if (
29 search.posts?.expected?.data === 'client' &&
30 typeof window === 'undefined'
31 ) {
32 const error = `Expected beforeLoad for ${Route.id} to be executed on the client, but it is running on the server`
33 console.error(error)
34 throw new Error(error)
35 }
36 return {
37 posts: typeof window === 'undefined' ? 'server' : 'client',
38 search,
39 }
40 },
41 loader: ({ context }) => {
42 console.log(
43 `loader for ${Route.id} called on the ${typeof window !== 'undefined' ? 'client' : 'server'}`,
44 )
45β
46 if (
47 context.search.posts?.expected?.data === 'client' &&
48 typeof window === 'undefined'
49 ) {
50 const error = `Expected loader for ${Route.id} to be executed on the client, but it is running on the server`
51 console.error(error)
52 throw new Error(error)
53 }
54 return { posts: typeof window === 'undefined' ? 'server' : 'client' }
55 },
56 component: () => {
57 const search = Route.useSearch()
58 const loaderData = Route.useLoaderData()
59 const context = Route.useRouteContext()
60 if (
61 typeof window === 'undefined' &&
62 search().posts?.expected?.render === 'client-only'
63 ) {
64 const error = `Expected component for ${Route.id} to be executed on the client, but it is running on the server`
65 console.error(error)
66 throw new Error(error)
67 }
68 return (
69 <div data-testid="posts-container">
70 <h3 data-testid="posts-heading">posts</h3>
71 <div>
72 ssr: <b>{JSON.stringify(search().posts?.ssr ?? 'undefined')}</b>
73 </div>
74 <div>
75 expected data location execution:{' '}
76 <b data-testid="posts-data-expected">
77 {search().posts?.expected?.data}
78 </b>
79 </div>
80 <div>
81 loader: <b data-testid="posts-loader">{loaderData().posts}</b>
82 </div>
83 <div>
84 context: <b data-testid="posts-context">{context().posts}</b>
85 </div>
86 <hr />
87 <Outlet />
88 </div>
89 )
90 },
91})