DEV Community

Cover image for Making clean API requests to the Backend with URLSearchParams in React.
Sushil Bajracharya
Sushil Bajracharya

Posted on

Making clean API requests to the Backend with URLSearchParams in React.

In the earlier days of crafting URLs in my React projects, I leaned on the trusty technique of String Interpolation for wrangling those pesky URL parameters. Sure, it got the job done, but deep down, it felt a bit off, like wearing mismatched socks – functional working, yet not quite right. The code lacked the finesse I yearned for, and as the project grew, the unease lingered. If you've ever sensed that discomfort when using String Interpolation for URL parameters, you're not alone. Let's explore a more fitting solution that not only does the job but does it with a touch of elegance.

rachel tada

Enter ---> a cleaner and more structured approach using URLSearchParams in React.

"URLSearchParams" is a built-in JavaScript object that allows you to work with the query string of a URL. It provides methods for appending, deleting, getting, and setting key-value pairs in the query string.

Here is how we can utilize URLSearchParams for clean API.

 const queryParams = new URLSearchParams();
 queryParams.append("limit", "10");
 queryParams.append("offset", offset);
 if (isActive) {
   queryParams.append("active", "true");
 }

 const params = `?${queryParams.toString()}`;
 const url = `${api}${params}`;
Enter fullscreen mode Exit fullscreen mode

We create a new instance of URLSearchParams to manage our URL parameters. The append method adds parameters to the URLSearchParams instance. Here, we add "limit" with a static value of "10," "offset" with a dynamic value, and "active" conditionally. The if (isActive) statement ensures that the "active" parameter is appended only if the isActive variable is truthy. We construct the query string using queryParams.toString(). Finally, we combine the base API URL (api) with the constructed query string to form the complete URL.

Advantages:

  1. Structured Parameters: Each parameter is appended individually, enhancing readability.
  2. Conditional Appending: Conditions for appending parameters are clearer.
  3. Dynamic Values: Easily accommodates dynamic values.
  4. Automatic Encoding: Takes care of encoding special characters, reducing the risk of errors.

While both approaches achieve the same result, the URLSearchParams approach is cleaner, more readable, and easier to maintain, especially as our project complexity increases. If you have found a better way, feel free to share it in the COMMENTS. Do REACT and FOLLOW ME to hear more from me.

REFERENCE:
UrlSearchParams in JS
What is urlsearchparams in javascript

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay