tomwyr
tomwyr10mo ago

`useQuery` in client components

I have a very simple app with a single page configured to use SSR. The component that the page renders requests data using the tRPC client and useQuery function. I modified the component to be a client component by adding use client on top of the file. The result I expected to see was app fetching the component from the server and loading data asynchronously from the client. Instead, the server's response is delayed until the data is loaded and the browser renders component with the data already loaded. Is it possible to use the combination of tRPC + SSR + use client? If so, wouldn't the code below result in the behavior I was expecting?
// src/pages/index.tsx
"use client";

import { trpc } from "../utils/trpc";

export default function HomePage() {

// Expecting to see "Loading..." first but the message is displayed immediately after
// a 2 seconds delay before rendering the page for the first time.

const result = trpc.greeting.useQuery({
name: "Bob",
});

if (!result.data) {
return <div>Loading...</div>;
}

return <div>{result.data.message}</div>;
}
// src/pages/index.tsx
"use client";

import { trpc } from "../utils/trpc";

export default function HomePage() {

// Expecting to see "Loading..." first but the message is displayed immediately after
// a 2 seconds delay before rendering the page for the first time.

const result = trpc.greeting.useQuery({
name: "Bob",
});

if (!result.data) {
return <div>Loading...</div>;
}

return <div>{result.data.message}</div>;
}
// src/pages/apis/trpc/[trpc].ts
const appRouter = router({
greeting: publicProcedure
.query(async ({ input }) => {
await new Promise((resolve) => setTimeout(resolve, 2000));

return {
message: `Hello ${input.name}!`,
};
}),
});
// src/pages/apis/trpc/[trpc].ts
const appRouter = router({
greeting: publicProcedure
.query(async ({ input }) => {
await new Promise((resolve) => setTimeout(resolve, 2000));

return {
message: `Hello ${input.name}!`,
};
}),
});
// src/utils/trpc.ts
export const trpc = createTRPCNext<AppRouter>({
config(opts) {
const { ctx } = opts;

return {
links: [
httpBatchLink({
// ...
}),
],

queryClientConfig: {
// ...
},
};
},

ssr: true,
});
// src/utils/trpc.ts
export const trpc = createTRPCNext<AppRouter>({
config(opts) {
const { ctx } = opts;

return {
links: [
httpBatchLink({
// ...
}),
],

queryClientConfig: {
// ...
},
};
},

ssr: true,
});
0 Replies
No replies yetBe the first to reply to this messageJoin