Skip to content

Commit

Permalink
Merge pull request #13 from gonta1026/search/ssr
Browse files Browse the repository at this point in the history
SSRでデータの取得を一度だけしたい。(サーバーの呼び出し画面訪問時だけにしたい)
  • Loading branch information
gonta1026 authored Aug 10, 2024
2 parents aeef118 + f1e5425 commit 0c157ab
Show file tree
Hide file tree
Showing 9 changed files with 50 additions and 27 deletions.
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
### set up
package install
```
yarn install
```

DBの起動
```
docker compose up -d
```
マイグレーション実行
```
npx prisma migrate dev
```
型の生成
```
npx prisma generate
```

### git cz
gitのコミットやりやすくなります。
```
Expand All @@ -14,4 +28,3 @@ npm install -g git-cz
git cz
```

### db set up
4 changes: 3 additions & 1 deletion next.config.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {}
const nextConfig = {
reactStrictMode: false,
}

export default nextConfig
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
"test": "npm-run-all --parallel --continue-on-error --print-name test:*",
"seed": "ts-node --compiler-options '{\"module\":\"CommonJS\"}' prisma/seed.ts",
"seed2": "ts-node prisma/seed.mjs",
"reset": "ts-node prisma/reset.ts"
"reset": "ts-node prisma/reset.ts",
"studio": "npx prisma studio"
},
"dependencies": {
"@heroicons/react": "^2.1.5",
Expand Down
17 changes: 6 additions & 11 deletions src/app/components/latestUser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,16 @@ import { type FC, useState } from 'react'
import { api } from '@/trpc/react'
import styles from '../index.module.css'
import { errorHandler } from '@/lib/error/errorHandler'
import type { User } from '@prisma/client'

type Props = {
latestUser: User
}

export const LatestUser: FC<Props> = ({ latestUser }) => {
const [user] = api.user.hello.useSuspenseQuery({ text: 'hello', id: 5 })
export const LatestUser: FC = () => {
// const [user] = api.user.hello.useSuspenseQuery({ text: 'hello', id: 5 })
const utils = api.useUtils()
const [name, setName] = useState('')
const [email, setEmail] = useState('')

const createPost = api.user.create.useMutation({
onSuccess: async () => {
await utils.user.invalidate() // 再取得
await utils.user.hello.invalidate()
setName('')
setEmail('')
},
Expand All @@ -28,11 +23,11 @@ export const LatestUser: FC<Props> = ({ latestUser }) => {

return (
<div className={styles.showcaseContainer}>
{user ? (
<p className={styles.showcaseText}>Your most recent post: {user.name} です</p>
{/* {user ? (
<p className={styles.showcaseText}>useSuspenseQueryのusername: {user.name} です</p>
) : (
<p className={styles.showcaseText}>You have no posts yet.</p>
)}
)} */}

<form
onSubmit={(e) => {
Expand Down
2 changes: 2 additions & 0 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export const metadata: Metadata = {
description: 'Generated by create next app',
}

export const dynamic = 'force-dynamic'

export default function RootLayout({
children,
}: Readonly<{
Expand Down
25 changes: 16 additions & 9 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,31 @@ import Link from 'next/link'
import { LatestUser } from '@/app/components/latestUser'
import styles from './index.module.css'
import { api } from '@/trpc/server'
// import { api as reactApi } from '@/trpc/react'
import type { FC } from 'react'

export const metadata = {
title: 'next template',
}

function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}

export const SometimesSuspend: FC = () => {
if (Math.random() < 0.5) {
throw sleep(1000)
}
return <p>Hello, world!</p>
}

export default async function Home() {
const latestUser = await api.user.first()
// const user = await api.user.hello({ text: 'hello', id: 5 })
const user = await api.user.hello({ text: 'hello', id: 5 })
const user = await api.user.hello({ text: 'hello', id: 1 })

return (
<main className={styles.main}>
<h1>Hello World🚀</h1>
<p style={{ color: 'white' }}>
id: {user?.id}
name: {user?.name}
</p>
<p style={{ color: 'white' }}>SSRで取得をしている name: {user?.name}</p>
{/* <p style={{ color: 'white' }}>user2 SSRで取得をしている name: {user2?.data?.name}</p> */}
<div className={styles.container}>
<h2 className={styles.title}>
Create <span className={styles.pinkSpan}>T3</span> App
Expand All @@ -43,7 +50,7 @@ export default async function Home() {
{/* <p className={styles.showcaseText}>{hello ? hello.greeting : 'Loading tRPC query...'}</p> */}
</div>
<Link href={'/sample'}>to sample page</Link>
{latestUser && <LatestUser {...{ latestUser }} />}
<LatestUser />
</div>
</main>
)
Expand Down
5 changes: 4 additions & 1 deletion src/trpc/query-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ export const createQueryClient = () =>
queries: {
// With SSR, we usually want to set some default staleTime
// above 0 to avoid refetching immediately on the client
staleTime: 120 * 1000,
enabled: false,
staleTime: 0,
refetchOnWindowFocus: false,
// staleTime: 2 * 1000,
},
dehydrate: {
serializeData: SuperJSON.serialize,
Expand Down
4 changes: 2 additions & 2 deletions src/trpc/react.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { QueryClientProvider, type QueryClient } from '@tanstack/react-query'
import { loggerLink, unstable_httpBatchStreamLink } from '@trpc/client'
import { createTRPCReact } from '@trpc/react-query'
import type { inferRouterInputs, inferRouterOutputs } from '@trpc/server'
import { useState } from 'react'
import { type ReactNode, useState } from 'react'
import SuperJSON from 'superjson'

import type { AppRouter } from '@/server/api/root'
Expand Down Expand Up @@ -39,7 +39,7 @@ export type RouterInputs = inferRouterInputs<AppRouter>
*/
export type RouterOutputs = inferRouterOutputs<AppRouter>

export function TRPCReactProvider(props: { children: React.ReactNode }) {
export function TRPCReactProvider(props: { children: ReactNode }) {
const queryClient = getQueryClient()

const [trpcClient] = useState(() =>
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
"exclude": ["node_modules", ".next"]
}

0 comments on commit 0c157ab

Please sign in to comment.