DEV Community

Krzysztof Żuraw
Krzysztof Żuraw

Posted on • Originally published at krzysztofzuraw.com on

Today I Learned - query string library have stringifyUrl

I’ve been using query-string library to create myquery string for a long time. Normally I’ve used it as follows:

import * as qs from 'query-string';

const API_URL = '/users?' + qs.stringfy({ user: '1' });
// API_URL will be /users?user=1
Enter fullscreen mode Exit fullscreen mode

Everything was fine until my parameter was null or undefined. When such case occurs my API_URLlooked something like /users?. It wasn’t a problem for the endpoint - the request was hitting backendyet I’ve some feeling that it can be done better. Today when I was integrating query-string intoa new project I found out about new function: stringifyUrl. Let’s see it in action:

import * as qs from 'query-string';

const API_URL = qs.stringifyUrl(
  {
    url: '/users',
    query: {
      user: 1,
    },
  },
  { skipNull: true }
);
// API_URL will be /users?user=1
// and in case when user id is null
// /users
Enter fullscreen mode Exit fullscreen mode

Perfect 🎉. Now I’m happy and I’ve learned new stuff - so if you happen to use query-string consider using stringifyUrl.

Top comments (0)