How to Use addQueryArgs to Simplify JavaScript URL Construction

If you’re familiar with WordPress development, you’ve likely used the add_query_arg() function in PHP. It’s an incredibly convenient tool for adding new query parameters to a URL and retrieving the modified result.

With the evolution of the Gutenberg editor, WordPress has ported this essential function to JavaScript. The JS version is named addQueryArgs and is part of the @wordpress/url library. In this article, I’ll demonstrate how to use this function to streamline your frontend development.

First, you need to add the library to your project’s dependencies:

npm install @wordpress/url --save

Once installed, you can import and use the addQueryArgs function in your project:

import { addQueryArgs } from '@wordpress/url';

The following example is a method from a Nuxt project we developed. It’s used to filter data based on multiple conditions. We first define an object for the default parameters, then dynamically add elements based on user selections. Finally, we pass this object to addQueryArgs to construct a clean URL for a REST API request.

fetchData() {
  let args = {
    'per_page'    : this.limit,
    'page'        : this.page,
    'categories'  : '9,10,11,12,13',
    'tax_relation': 'AND',
  };

  if (this.orderBy) {
    args.orderby = this.orderBy;
  }

  if (this.type) {
    args.huxing = this.type;
  }

  let exclude_cats = _.difference(_.rest(_.pluck(this.storeOptions, 'value')), [this.store]);

  if (this.store) {
    args.categories_exclude = exclude_cats;
  }

  if (this.level) {
    args.tags = this.level;
  }

  return this.$api.get(addQueryArgs('/api/posts', args));
},

As you can see, this approach is far superior to traditional string concatenation in JavaScript. The code is much more readable, the logic is clearer, and it’s significantly easier to maintain over time.

Beyond addQueryArgs, the @wordpress/url library offers several other practical functions for URL manipulation, such as getQueryArgs and getQueryString. If you find yourself handling complex URLs in your frontend projects, I highly recommend giving this library a try.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *