1

So, currently, I have a routing component:

<Route path="/lists/:query" component={Lists} />

I get a call like:

http://localhost:4567/lists/page=17&city_codes=2567

In my Lists component, I handle this query in this way:

componentDidMount() {
  const query = match.params.query;
  const cleanQueryString = query.replace(/[|;$%@"<>()+,]/g, '');
  // break up the string using '&' and '=' into an object
  const properties = this.queryURL(cleanQueryString);
  const cleanQueryObj = _.pick(Object.assign({}, ...properties), [
  'page',
  'city_codes',
  'min_monthly_fee',
  'max_monthly_fee',
  'order_by',
]);

  // update the query object based on component state
  this.setState({ query: cleanQueryObj }, () => {
    cleanQueryObj.page && this.updateIndex(parseInt(cleanQueryObj.page, 10));
  });
  // call axios request and update redux
  dispatch(handleLists(cleanQueryObj));
  // update browser url
  this.props.history.push(cleanQueryObj);

Now, I see a lot of major sites using ?q= before the query and I'm wondering what I'm missing or what could be improved?

Thoughts?

1 Answer 1

1

While what you are doing is technically valid, it is a bit non-standard. The way you use the router :query param and the way it is formatted, reaaaaly looks like an actual location.search parameter format, and not a path parameter.

A more standard way to do it, would be with the following URL:

http://localhost:4567/lists?page=17&city_codes=2567

And code as follow:

// In your routes, just a simple route with no path params
<Route path="/lists" component={Lists} />

// In your component
import queryString from 'query-string'

[...]

componentDidMount() {
  // Use location object from react-router
  const { search } = this.props.location 
  // Parse it using a npm dedicated module
  const { page, city_codes } = queryString.parse(search)
  // Now you can use those params
]);

Edit: and now an actual answer to the question:

?q=blah is usually used in a search context, with q parameter being a string used to search something. There can be other parameters following for example ?q=blah&ext=txt.

It is hence different from your :query path param, which is encoded to contain multiple parameters, while q here is a single ready-to-use parameter.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.