No more parsing of query strings in V4?
I just upgraded from V4 alpha to beta (hooray!), but I can't find the location.query object anymore, only a location.search string. Have I missed something, or do I have to do my own parsing now?
I have just discovered the same thing, and was rather surprised. I understand that the ?a=x&b=y query format isn't part of the URL standard de–jure, but it has been a de–facto standard for twenty years, and is how most almost every app handles supplying non-hierarchical params. If React Router's goal is to handle syncing the URL with the UI, then it seems like a strange omission to leave this completely up to the user.
I've seen it mentioned that history could be modified to add query parsing support back in, but without any suggestion how. Seems like an example be useful here, at the very least. Particularly since this is a regression in v4 compared to earlier versions.
There are a number of popular packages that do query string parsing/stringifying slightly differently, and each of these differences might be the "correct" way for some users and "incorrect" for others. If React Router picked the "right" one, it would only be right for some people. Then, it would need to add a way for other users to substitute in their preferred query parsing package. There is no internal use of the search string by React Router that requires it to parse the key-value pairs, so it doesn't have a need to pick which one of these should be "right".
I don't know of a great way to add automatic query parsing to the history instance, but I think that you could listen for location changes and modify the history.location object to add the query property. I obviously haven't tested it, but it should work.
Having included that, I do think that it would just make more sense to just parse location.search in your view components that are expecting a query object.
Edit I removed the sample code since people are pointing out that it had issues. It was just something that I wrote in a minute or two without actually testing, so I don't want more people to keep running into problems because of it. The qhistory package that I link to below should be a better example since it is actually tested.
Solid answer, thank you @pshrmn :)
Sorry, but I just do not follow the logic here. Path params and query string params are two equally valid and popular ways of supplying data through the URL. If the purpose of the library is to support syncing the URL to the UI, then why is parsing and binding one type of param to the match object considered in scope, and the other not? Why only solve half the problem?
Nor do I see any reason why a user would need to supply a particular query string parsing library, any more than they would need to override the router's current path parsing algorithm. They would simply need to use the query string in the way that the router expected, just as they currently have to use the path in the way the router expects.
@jonrimmer We've had many, many requests over the years to modify the way we handle query string parsing and serialization. Just had another one (for v3) this morning, in fact! Just because you don't see it, doesn't mean people don't have different needs.
Also, it's incredibly easy for you to provide your own solution here.
import stringifyQuery from 'whatever-lib-you-want'
<Link to={{ pathname: '/the/path', search: stringifyQuery({ your: 'query' }) }}>click me</Link>
Still too much work?
const QueryLink = (props) => (
<Link {...props} to={{ ...props.to, search: stringifyQuery(props.to.query) }}/>
)
Now you can
<QueryLink to={{ pathname: '/the/path', query: { go: 'nuts' } }}>click me</QueryLink>
One thing that's become cumbersome in v4 is creating links with some query parameters updated. With v3, I used to do
this.props.push({
pathname: this.props.location.pathname,
query: Object.assign({}, this.props.location.query, { foo: "bar" })
});
That means that all other potential query parameters stay in place. I haven't found an equally simple way to do that in v4.
@jochenberger It's literally just
this.props.push({
pathname: this.props.location.pathname,
search: stringifyQuery(Object.assign({}, parseQueryString(this.props.location.search), { foo: "bar" }))
});
And if that's still too much work, you can wrap it up in a component as I demonstrated in https://github.com/ReactTraining/react-router/issues/4410#issuecomment-276427066
Thanks, I ended up writing a helper function doing about that. Of course, doing it like this means that you have to parse location.search for every link, but that can be solved by a HOC that parses location.search and passes the result as location.query or passes individual query parameters as props (this is what I did).
I guess that sooner or later there's going to be third-party modules doing just that.
I don't mean to beat a dead horse, but this is kind of a bummer 😕 I'd prefer an opinionated solution over no built in solution. The way v3 handled it was good. Ah well, for now looks like the query-string library mentioned above is all I really need.
Thanks all for the hard work on v4! It would be good to document this behavior for future adopters, query strings being as popular a feature as they are—had to dig a bit to find this thread.
@rubencodes The approach being taken for 4.0 is to strip out all the "batteries included" kind of features and get back to just basic routing. If you need query string parsing or async loading or Redux integration or something else very specific, then you can add that in with a library specifically for your use case. Less cruft is packed in that you don't need and you can customize things to your specific preferences and needs.
This is a very important topic. Most routing libs handle query params. I fully understand the reasons against it in v4 and totally support it.
For those coming from those other libs, and especially v3 - it might be worth it to mention this whole topic (or at least https://github.com/ReactTraining/react-router/issues/4410#issuecomment-276427066 and https://github.com/ReactTraining/react-router/issues/4410#issuecomment-276630264 )in the docs though. I searched for this for two days (I am horrible at searching, first place I looked was docs)
This comment here in this topic was also very very helpful to me to understanding v4 methodology - https://github.com/ReactTraining/react-router/issues/4527#issuecomment-279541628
The other thing I struggled with was picking the query string lib. I found this great topic that told the difference between qs and query-string node modules - http://stackoverflow.com/q/29136374/1828637
FYI: For a lot of cases URLSearchParams is good enough.
const search = props.location.search; // could be '?foo=bar'
const params = new URLSearchParams(search);
const foo = params.get('foo'); // bar
We use the https://github.com/jerrybendy/url-search-params-polyfill for older browsers which works great with webpack.
Ok for not including query string parsing inside React Router but since this is a very common use case, it should be documented here.
I'm really missing the query, and I think many other users expect this to be a core functionality in a router. Currently I see only two suboptimal possibilities, either like @donaldpipowitch, getting the query via URLSearchParams and setting link search by stringifying query on each of your Links (pretty inefficient!) or overriding router components (e.g. Link, withRouter), something like:
export const Link = (props) => {
if (props.to && props.to.query) {
props.to.search = stringifyQuery(props.to.query);
delete props.to.query;
}
return <LinkLegacy {...props} />;
};
export const NavLink = (props) => {
if (props.to && props.to.query) {
props.to.search = stringifyQuery(props.to.query);
delete props.to.query;
}
return <NavLinkLegacy {...props} />;
};
export const withRouter = (WrappedComponent) => {
@withRouterLegacy
class WithRouter extends Component {
static contextTypes = {
router: PropTypes.shape({
history: PropTypes.shape({
push: PropTypes.func.isRequired,
replace: PropTypes.func.isRequired,
createHref: PropTypes.func.isRequired
}).isRequired
}).isRequired,
};
push = (propsTo) => {
const to = { ...propsTo };
if (to.query) {
to.search = stringifyQuery(to.query);
delete to.query;
}
this.context.router.history.push(to);
}
replace = (propsTo) => {
const to = { ...propsTo };
if (to.query) {
to.search = stringifyQuery(to.query);
delete to.query;
}
this.context.router.history.replace(to);
}
render() {
const { location } = this.props;
location.query = parseQuery(location.search);
return (
<WrappedComponent {...this.props} router={{ ...this.context.router, push: this.push, replace: this.replace }} />
);
}
}
return WithRouter;
};
I don't find either satisfying. Why not give a possibility to define parseQuery/stringifyQuery on the wrapper components (BrowserRouter, StaticRouter, ..) and use these instead of stripping query completely @timdorr ?
And what about having another package like react-router-extra that includes location.query, LinkQuery... and other common use cases (in an opinionated manner) without polluting core?
@tkrotoff You can try qhistory.
Ty Donald for that post. Adding a late comment for anyone else searching this post for how to update their code, and they aren't sure what package to grab, 'query-string' is simple one, and worked for me after searching some recommendations on stack overflow.
I love React, and so far love all the v4 changes. in this however, complete opinion: The team made an overthinking move to get rid of this awesome and simple feature. I love that v4's goal is to simplify, so this thinking does the opposite, just to satisfy the loud minority. Sends the signal that if we send them enough emails they will change things to how we want them.
I fully understand it, but I'd say the quiet majority of us who haven't been emailing are against any 'upgrades' that make us add lines to our code. Despite that, I still appreciate all the hard work the team does! I feel I have no room to complain because the team made it in the first place :)
@pshrmn This has a bug
const history = createBrowserHistory()
// register the first listener. These are called synchronously, so
// the next listener won't be called until this has finished
history.listen(() => {
history.location = Object.assign(history.location,
// parse the search string using your package of choice
{ query: parseQueryString(history.location.search) }
)
})
when a user refresh the browser. history.listen doesn't trigger so the location.query === undefined .how to get location.query when get the page at the first visit .
You can use this to decode query String
const query = decodeURIComponent(this.props.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURIComponent("redirect"/* Query want to decode*/).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1")
@lcoder Add the query outside the listener.
function addLocationQuery(history){
history.location = Object.assign(
history.location,
{
query: parseQueryString(history.location.search)
}
)
}
addLocationQuery(history);
history.listen(() => {
addLocationQuery(history)
})