How to Delay Queries Until After User Provisioning?
Hi everyone, I'm new to TanStack Query (v5) and currently integrating it into a React frontend that uses MSAL.js for authentication with Azure AD.
After users successfully log in via MSAL, I need to call a POST /users/provision endpoint to create or update them in the backend. This provisioning step fetches role information, ensures the user is stored in the DB, and returns their data. Only after that should the rest of my app start loading anything else.
The issue is that React Query hooks like useCurrentUser, useSmsCredits, useSmsLogs etc. run immediately and make requests before provisioning is complete. This causes race conditions and unauthorized errors, especially when it's the user’s first login.
What I want is this: when a user logs in, the frontend should call /users/provision once and only after that allow the rest of the React Query system to run. If the user reloads the page while still logged in (session is kept in localStorage), only /me should be called to hydrate the user, no need to call provision again. But if they explicitly log out and then log back in, provision should run again to sync roles from Azure.
3 Replies
harsh-harlequinOP•7mo ago
I’m looking for a clean and correct way to block or delay queries until provisioning is done. I want to avoid problems like “React hooks must be called in the same order”, or “useAuth must be used within an AuthProvider”, or components like SmsDashboard crashing due to missing data.
The logic should guarantee that on first login, provision runs before anything else. On page reload, only /me runs. On re-login after logout, provision runs again.
Right now I’m not sure how to coordinate this in TanStack Query. Should I use enabled: false in every hook and wait for a provision flag from context? Should I globally block queries in main.tsx? Is there a better design pattern?
I can attach key frontend files like main.tsx, auth-context.tsx, useCurrentUser.ts, App.tsx, SmsDashboard.tsx, and the individual query hooks like useSmsLogs.ts and useSmsCredits.ts if needed.
Would really appreciate help from someone more experienced with TanStack Query – thanks!
harsh-harlequinOP•7mo ago
I’ve summarized the relevant parts of the code in this GitHub Gist:
https://gist.github.com/okadriu/3451a19d25adedabce2c10eb468df087
Thank you very much!!!
harsh-harlequinOP•7mo ago
Does anyone know how I can solve this?