ensureQueryData in route loader and invalidating it
I have a route (_authenticated.tsx) that decides if it should return a Login page or a Layout page with the rest of the application (including the Outlet for the rest of the app). All routes that require authentication are under a folder with the same name (_authenticated).
This route has a loader that uses queryClient.ensureQueryData(...) to fetch a /me endpoint from the server. I get access to the returned data by const {data} = useSuspenseQuery(...) with the same queryKey. If the response doesn't have an authenticated user, the route shows Login. If the response has the user, the route renders the application with Outlet.
This all works fine. But. Then in the Login page functionality I post the login request to the server. And if the post is successful, my plan was to just use queryClient.invalidateQueries() in the mutate's onSuccess to make the _authenticated.tsx route to get the fresh data of the /me endpoint (with the logged in user) and it would show the Layout component rendering my app.
But this is where my approach doesn't work. The onSuccess is run and the queries are being invalidated. But the _authenticated.tsx route never gets the new fresh data from the cache.
The way I have fixed this is I skip the loader/ensureQueryData/useSuspenseQuery combo and just use the useQuery in my _authenticated.tsx route. This way the cache gets invalidated and the route is being re-rendered now with the logged in user.
I know this is all due to the lack of my understanding, but I would really like to understand the ensureQueryData and useSuspenseQuery better. Currently I don't use them at all because I don't trust I get the latest data where I use them.
So if anyone can help me understand this better and maybe even show a way how I could use them in my situation, that would be highly appreciated.
0 Replies