T
TanStack2y ago
passive-yellow

Retrieving the token from router context into an useGraphQL() wrapper around useQuery()

I tried to write and useQuery() wrapper so I can inject the logged user token. import request from "graphql-request"; import { type TypedDocumentNode } from "@graphql-typed-document-node/core"; import { useQuery, type UseQueryResult } from "@tanstack/react-query"; import { HASURA_ENDPOINT } from "../utils/config"; import { useRouteContext } from "@tanstack/react-router"; export function useGraphQL<TResult, TVariables>( document: TypedDocumentNode<TResult, TVariables>, ...[variables]: TVariables extends Record<string, never> ? [] : [TVariables] ): UseQueryResult<TResult> { const { authClient } = useRouteContext({ from: "__root__" }); return useQuery({ queryKey: [(document.definitions[0] as any).name.value, variables], queryFn: async ({ queryKey }) => { const token = authClient.GetTokenSilentlyOptions(); if (token === null) { throw new Error("Token is null"); } const requestHeaders = { authorization: Bearer ${token}, }; request(HASURA_ENDPOINT, document, queryKey[1] ? queryKey[1] : undefined, requestHeaders); }, }); } My router is like this const rootRoute = rootRouteWithContext<{ authClient: Auth0Client; queryClient: QueryClient; }>()({ component: Layout }) const patientRoute = new Route({ getParentRoute: () => authRoute, path: '/patients', component: PatientPage }) My patient page is export const PatientsPage = () => { const { data, isPending, isError } = useGraphQL(PatientListRouteQuery, null); I'm getting this erro Invariant failed: useMatch("root") is being called in a component that is meant to render the '/auth/patients' route. Did you mean to 'useMatch("root", { strict: false })' or 'useRoute("root")' instead?
3 Replies
passive-yellow
passive-yellowOP2y ago
Should I be getting this root context as thats the one with the context?
extended-salmon
extended-salmon2y ago
Just as it says. You must set strict to false because the useRouteContext call is inside a reusable component. Of course this is really a router question
passive-yellow
passive-yellowOP2y ago
Thanks mate

Did you find this page helpful?