T
TanStack9mo ago
xenial-black

Advice for creating query "middle ware"

Hello! I am using a "user" query as the auth state for my react application. I am using TS query and router with recent versions. I have many queries throughout my app, all of which I have only defined and exported queryOptions for. I have many useQuerys for authenticated endpoints that are mounted but manually disabled if the user isn't signed in to prevent failed GETs (by consuming the user query there and passing it in to queryOptions). This is getting tedious and I would like to think of a better solution to save time and ensure my team doesn't have to worry about manually disabling them. The two options I am considering are: 1. Creating custom hooks to export the authenticated endpoint queries with the auth check implemented internally.
2. Calling useQueryClient in my _root component and appending the default options to conditionally enable specific queries like below. I would prefer to do 2 since it would take much less time to implement but don't know if it would be an advisable practice. Has anyone every done something similar? Thanks for any tips!
function RootComponent() {
const queryClient = useQueryClient()
queryClient.setDefaultOptions({
queries: {
enabled(query) {
const user = queryClient.getQueryData('user')
if (user) return true

return !['/authed/1', '/authed/2'].includes(getQueryRoute(query.queryKey))
},
},
})
function RootComponent() {
const queryClient = useQueryClient()
queryClient.setDefaultOptions({
queries: {
enabled(query) {
const user = queryClient.getQueryData('user')
if (user) return true

return !['/authed/1', '/authed/2'].includes(getQueryRoute(query.queryKey))
},
},
})
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?