Created
September 23, 2022 01:07
-
-
Save tatsuyasusukida/5e527a86e7131b4f34f48ac1430ba882 to your computer and use it in GitHub Desktop.
Next.js tRPC example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { initTRPC } from "@trpc/server"; | |
import * as trpcNext from "@trpc/server/adapters/next"; | |
import { z } from "zod"; | |
export const t = initTRPC.create() | |
export const appRouter = t.router({ | |
hello: t.procedure | |
.input(z.object({ | |
text: z.string(), | |
})) | |
.query(({ input }) => { | |
return { | |
greeting: `Hello ${input.text}`, | |
} | |
}) | |
}) | |
export type AppRouter = typeof appRouter | |
export default trpcNext.createNextApiHandler({ | |
router: appRouter, | |
createContext: () => ({}), | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { AppProps } from 'next/app' | |
import '../styles/globals.css' | |
import { trpc } from '../utils/trpc' | |
function MyApp({ Component, pageProps }: AppProps) { | |
return <Component {...pageProps} /> | |
} | |
export default trpc.withTRPC(MyApp) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NextPage } from "next"; | |
import { trpc } from "../utils/trpc"; | |
const Client: NextPage = () => { | |
const hello = trpc.hello.useQuery({ text: 'tRPC' }) | |
return ( | |
<main> | |
{hello.data?.greeting} | |
</main> | |
) | |
} | |
export default Client |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createTRPCNext } from '@trpc/next' | |
import { httpBatchLink } from '@trpc/client' | |
import { AppRouter } from '../pages/api/trpc/[trpc]' | |
export const trpc = createTRPCNext<AppRouter>({ | |
config({ ctx }) { | |
return { | |
links: [ | |
httpBatchLink({ | |
url: '/api/trpc', | |
}), | |
], | |
} | |
}, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment