jkb
jkb
TtRPC
Created by jkb on 6/11/2024 in #❓-help
Header caching
My solution is to use a react useEffect to update the trpcClient
export const TRPCProvider: React.FC<{
children: React.ReactNode;
}> = ({ children }) => {
const auth = useAuthentication();
const [queryClient] = React.useState(() => new QueryClient());
const [trpcClient, setTrpcClient] = React.useState(() =>
api.createClient({
transformer,
links: [
httpBatchLink({
async headers() {
const token = auth.isAuthenticated
? await auth.getAccessToken()
: null;
console.log({ token, auth: auth.isAuthenticated });
return {
Authorization: token ? `${token}` : "",
};
},
url: `${getBaseUrl()}/api/trpc`,
}),
],
}),
);
React.useEffect(() => {
setTrpcClient(
api.createClient({
transformer,
links: [
httpBatchLink({
async headers() {
const token = auth.isAuthenticated
? await auth.getAccessToken()
: null;
console.log({ token, auth: auth.isAuthenticated });
return {
Authorization: token ? `${token}` : "",
};
},
url: `${getBaseUrl()}/api/trpc`,
}),
],
}),
);
}, [auth.isAuthenticated]);

return (
<api.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
</api.Provider>
);
};
export const TRPCProvider: React.FC<{
children: React.ReactNode;
}> = ({ children }) => {
const auth = useAuthentication();
const [queryClient] = React.useState(() => new QueryClient());
const [trpcClient, setTrpcClient] = React.useState(() =>
api.createClient({
transformer,
links: [
httpBatchLink({
async headers() {
const token = auth.isAuthenticated
? await auth.getAccessToken()
: null;
console.log({ token, auth: auth.isAuthenticated });
return {
Authorization: token ? `${token}` : "",
};
},
url: `${getBaseUrl()}/api/trpc`,
}),
],
}),
);
React.useEffect(() => {
setTrpcClient(
api.createClient({
transformer,
links: [
httpBatchLink({
async headers() {
const token = auth.isAuthenticated
? await auth.getAccessToken()
: null;
console.log({ token, auth: auth.isAuthenticated });
return {
Authorization: token ? `${token}` : "",
};
},
url: `${getBaseUrl()}/api/trpc`,
}),
],
}),
);
}, [auth.isAuthenticated]);

return (
<api.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
</api.Provider>
);
};
This feels wrong, but it is working. is there a better way of doing this?
3 replies