Reputation: 179
I'm having difficulties with TRPC (10.9.0) & tanstack/react-query (4.10.0) Next.js app. As other answers here suggested I wrapped my _app.tsx in <QueryClientProvider> but still get this error.
// _app.tsx
import { AppProps } from "next/app";
import { trpc, client } from "../src/services";
import { QueryClientProvider } from "@tanstack/react-query";
const App = ({ Component, pageProps }: AppProps) => {
return (
<QueryClientProvider client={client}>
<Component {...pageProps} />
</QueryClientProvider>
);
};
export default trpc.withTRPC(App);
// src/services/index.tsx
import { AppRouter } from "server";
import { createTRPCNext } from "@trpc/next";
import { httpBatchLink } from "@trpc/client";
import { QueryClient } from "@tanstack/react-query";
export const client = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
},
},
});
export const trpc = createTRPCNext<AppRouter>({
config() {
return {
links: [
httpBatchLink({
url: process.env.NEXT_PUBLIC_API_URL as string,
}),
],
};
},
ssr: false,
});
I'm using trpc query inside /pages/index.tsx
I was trying to add QueryClientProvider just as error message stated but no results
Upvotes: 1
Views: 1667
Reputation: 116
tRPC provides a built-in way to pass options to the QueryClient
it automatically constructs when using the createTRPCNext
method via the queryClientConfig
option:
export const trpc = createTRPCNext<AppRouter>({
config() {
return {
queryClientConfig: {
defaultOptions: {
queries: { staleTime: 5000, refetchOnWindowFocus: false },
},
},
links: [
httpBatchLink({
url: process.env.NEXT_PUBLIC_API_URL as string,
}),
],
};
},
ssr: false,
});
Alternatively, if you do want to construct the QueryClient
yourself, you can pass the query client in via the queryClient
option:
const client = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
},
},
});
export const trpc = createTRPCNext<AppRouter>({
config() {
return {
queryClient: client,
links: [
httpBatchLink({
url: process.env.NEXT_PUBLIC_API_URL as string,
}),
],
};
},
ssr: false,
});
With these options set, you don't need to use the QueryClientProvider
in your _app.tsx
and just revert to only trpc.withTRPC
. I.e.
// _app.tsx
import { AppProps } from "next/app";
import { trpc } from "../src/services";
const App = ({ Component, pageProps }: AppProps) => {
return (
<Component {...pageProps} />
);
};
export default trpc.withTRPC(App);
Upvotes: 2