How to pass URL encoded query params to fetch?

tips
fetch
tutorials

#1

Here’s a simple way to properly url encode and pass query string along with your request when you make an API using fetch module.

Add this function in your helpers module, or somewhere in your file

function buildUrl(url, parameters) {
    let qs = "";
    for (const key in parameters) {
        if (parameters.hasOwnProperty(key)) {
            const value = parameters[key];
            qs +=
                encodeURIComponent(key) + "=" + encodeURIComponent(value) + "&";
        }
    }
    if (qs.length > 0) {
        qs = qs.substring(0, qs.length - 1); //chop off last "&"
        url = url + "?" + qs;
    }

    return url;
}

and then when you use fetch module, use the above function to build the url, like this

.fetch(
    buildUrl("your url", {
        key: value,
        anotherKey: anotherValue
    }),
    {
        method: "GET",
        headers: {
            Authorization: token
        }
    }
)

Hope that helps! Cheers :slight_smile:


#2

It will be nice to have tips and tutorials tag in the form.

keep up the good work


#3

@ganas you mean post tags? I added those now