T
TanStack2y ago
ambitious-aqua

Cannot get context value on child route

I tried to set data from async on before load at root and tried to use it in child route but it cannot get anything from context. Did I do something wrong? https://stackblitz.com/edit/vitejs-vite-bnyapb
Nattanont Thammarangsie
StackBlitz
Tanstack Router Private Lab - StackBlitz
Next generation frontend tooling. It's fast!
No description
No description
No description
7 Replies
frail-apricot
frail-apricot2y ago
Although you are fetching the user in the __root route, you aren't the result of the profile fetch into your auth-context.
No description
frail-apricot
frail-apricot2y ago
and this isn't reflected on the index page, since you are consuming useAuth whilst it hasn't had the user added into it.
ambitious-aqua
ambitious-aquaOP2y ago
What should I do if I want to get data from server to check current user profile and get it on child route?
frail-apricot
frail-apricot2y ago
What do you mean? If you set the current user's profile from the __root route into your authContext, you can then in your child routes, read the value of context.auth and have the profile stated there.
ambitious-aqua
ambitious-aquaOP2y ago
Do you mean if I want to get data from context.auth then I should send via loader?
frail-apricot
frail-apricot2y ago
No. You can still access it in the beforeLoad callback. There is a difference between the Router context and React context. Its just that you happen to be injecting the React context into the Router's context, which is totally fine. Then its just a matter is choosing what is your source-of-truth. Since you don't want to be storing the user data in both the Router's context as well as React's, because you then open yourself up to potential drift.
ambitious-aqua
ambitious-aquaOP2y ago
OK, I understand about Router context and React context. I can access Router context via Route.useRouteContext(). I'm so grateful for your help.

Did you find this page helpful?