jkb
Header caching
My solution is to use a react useEffect to update the trpcClient
This feels wrong, but it is working. is there a better way of doing this?
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>
);
};
3 replies