Router and context question
Schmell opened this issue · comments
I am trying to wrap routes with a context provider and i am getting errors.
Is this possible with preact-router??
const MyContext = createContext()
...
<Router>
<MyContext.Provider>
<Route path="/somepath" component={SomeComp}/>
</MyContext.Provider>
...
Could you be a bit more specific than "getting errors"?
That should work just fine.
TypeError: Cannot read properties of undefined (reading 'replace')
at segmentize (util.js?4228:69:1)
at rank (util.js?4228:77:1)
at rankChild (util.js?4228:81:1)
at prepareVNodeForRanking (util.js?4228:64:1)
at Array.filter (<anonymous>)
at Router.getMatchingChildren (index.js?a178:208:1)
at Router.render (index.js?a178:227:1)
Ah, my bad.
Children of <Router>
need to be routes. Context will need to wrap the router.
Ya i knew that worked, but in my case it will put all variables on the an almost global scope.
I think i can do it with nested routes, I just have to get used to the idea of having routes all over the place
That's usually the point of context, to put values on a global scope. If you just want to provide a context for a single route, why not put the <MyContext.Provider>
within the route component itself, rather than wrapping the route?
Nested routes, AFAIK, are not supported.
Ya i hear what you are saying, but i want to share some values between routes and ideally only these routes.
Here is a better example of what i am trying to do.
const GlobalContext = createContext()
const MyContext = createContext()
...
const [gloabalContext, setGlobalContext] = useState({})
const [myContext, setContext] = useState({})
<GlobalContext.Provider value={{gloabalContext, setGlobalContext}}
<Router>
<Route path="/" component={Home}/>
...other routes
<MyContext.Provider value={{myContext, setMyContext}}>
<Route path="/somepath" component={SomeComp}/>
<Route path="/otherpath" component={OtherComp}/>
</MyContext.Provider>
... more routes etc...
</Router>
</GlobalContext.Provider>
...
Other routers definitely have this ability as i am trying to do this based on a tut is saw.
I am reading the preact-router docs and there is a section on nested routers
https://github.com/preactjs/preact-router#nested-routers
That being said i have not made it work so far. Of course there is probably another way to do this. I just liked this approach when i saw it
Thanks for your help guys!!
Other routers definitely have this ability
preact-router
has historically been a very simple router, not supporting features that many others have (you can usually use them in place of preact-router
)
I am reading the preact-router docs and there is a section on nested routers
Ah, missed that, you're totally right. I'll correct that comment.
Hey thanks. I might switch, but for now i want to try to stay in the preact ecosystem if i can.
You could switch over to preact-iso
which better supports this and, in general, is recommended over router here nowadays.