frontarm / navi

🧭 Declarative, asynchronous routing for React.
https://frontarm.com/navi/
MIT License
2.07k stars 71 forks source link

How to pass context into Router when using useContext hooks + static rendering? #168

Open jacobedawson opened 4 years ago

jacobedawson commented 4 years ago

I'm currently having trouble trying to add authentication guards to my routes in an app that has been setup for static rendering (which, btw is itself not working due to issue https://github.com/frontarm/navi/issues/92).

My app is integrated with Auth0 and receives auth state via a useContext hook. However, to pass Navi context I have to add it to the Router component. The Router component is rendered in the async main function, which sits on the register function in order to handle static rendering. However, Hooks can only be used within functional components, so I could place the Router component in a functional component, except the Router component needs to await the navigation.getRoute function.

Now I have multiple levels of components trying to pass around this context, which still doesn't seem to be appearing in the map callback of my routes definition.

I switched to Navi from React Router yesterday due to the enticing promise of easy static rendering and a declarative API, but at the moment I am just chasing my tail, and I can't find any relevant combination of topics (i.e. static rendering + context) in the docs. I have seen something about setContext mentioned (https://frontarm.com/navi/en/reference/navigation/#navigationsetcontext), but it's hard to put all these pieces together and make sense of what's actually happening.

If anyone can point me in the right direction I'd appreciate it! Otherwise it might be back to React Router.

jamesknelson commented 4 years ago

Sorry about the delay in replying to this one. Access to context is indeed a big problem, and it's something I'm not sure is easy to fix with the Navi architecture.

The issue is, Navi is designed to work externally from React, and inject the resulting state into different points in the React tree – a little like Redux and connect(). Unfortunately, this makes it difficult to access anything in context.

My current thought on this is that it probably makes sense to also handle authentication state externally from React. Ideally, Navi should be a generalized middleware tool that can handle authentication and navigation, and then transparently inject these into React context. I'll have more on this soonish with Navi 1.0.