Router Context is Swallowed
See original GitHub issueI am here to resurrect #19 and #16, for which I apologize.
I believe the current state of things is that mobx (and mobx-react-router) don’t really work out of the box with react-router v4.
Cause:
observer
components use a customized shouldComponentUpdate
that pays attention to the mobx context but not the context that react-router needs.
Here’s a repro:
- Code: https://gist.github.com/dleavitt/518b624d49c6bff7c2d7ee2782607ce3#file-sandbox-ts
- CodePen: https://codepen.io/pygmael/pen/BZwyGG
Current workaround:
Users of this lib should wrap withRouter
around every observer in their app.
Solutions:
Though this isn’t mobx-react-router
’s fault (ReactTraining/react-router#4781, etc, etc) it does appear that this library owns the space at the intersection of mobx and react-router and is therefore in the best position to bundle a fix or workaround.
Short-term solution: This should be called out prominently in the readme. It’s relevant to ~100% of people who use this lib (I think?)
Longer-term solutions: A fix or workaround should be integrated into this lib if possible. I think it is possible! Anything is possible, right? Here are some potential approaches:
- Whatever
react-router-redux
does. Assuming it has this problem solved, which I haven’t verified. - As part of
syncHistoryWithStore
, somehow turn the history attributes that react-router uses intoobservable
s. If that’s a thing. - Add a function/decorator that takes the context react-router needs out of the routing store and puts it into the routing context of the child component. You’d still need to apply this decorator to anything that uses a
Route
orNavLink
, but at least you don’t have to wrap every singleobserver
inwithRouter
. - Provide a router-friendly alternative to
observer
as part of this lib. This at least provides a solution out of the box and gets people like me to stop writing our own dubious one-offs.
Happy to submit a PR for the README or to look into options 3/4 if you agree with the above.
Thanks! Daniel
Issue Analytics
- State:
- Created 6 years ago
- Reactions:1
- Comments:12 (5 by maintainers)
Does someone have a complete working example of this workaround? Been playing with this for the past hours and still did not manage to make the whole thing work together…
@clementdevosmc Notice the
@withRouter
wrapped wrapped round certain components. Worth reading this to understand the problem: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/blocked-updates.md