65

I am making a request like this:

fetch("https://api.parse.com/1/users", {  method: "GET",  headers: headers,     body: body})

How do I pass query string parameters? Do I simply add them to the URL? I couldn't find an example in thedocs.

Sarun UK's user avatar
Sarun UK
6,7667 gold badges26 silver badges51 bronze badges
askedMay 14, 2016 at 18:45
Guy's user avatar
1

7 Answers7

76

Your first thought was right: just add them to the URL.

Remember you can use template strings (backticks) to simplify putting variables into the query.

const data = {foo:1, bar:2};fetch(`https://api.parse.com/1/users?foo=${encodeURIComponent(data.foo)}&bar=${encodeURIComponent(data.bar)}`, {  method: "GET",  headers: headers,   })
answeredMay 14, 2016 at 18:48
Ben Clayton's user avatar
Sign up to request clarification or add additional context in comments.

Comments

41

Short answer

Just substitute values into the URL like this:

const encodedValue = encodeURIComponent(someVariable);fetch(`https://example.com/foo?bar=${encodedValue}`);

Longer answer

Yes, you just need to add the query string to the URL yourself. You should take care to escape your query string parameters, though -don't just construct a URL like

`https://example.com/foo?bar=${someVariable}`

unless you're confident thatsomeVariable definitely doesn't contain any&,=, or other special characters.

If you were usingfetch outside of React Native, you'd have the option of encoding query string parameters usingURLSearchParams. However, React Nativedoes not supportURLSearchParams. Instead, useencodeURIComponent.

For example:

const encodedValue = encodeURIComponent(someVariable);fetch(`https://example.com/foo?bar=${encodedValue}`);

If you want to serialise an object of keys and values into a query string, you could make a utility function to do that:

function objToQueryString(obj) {  const keyValuePairs = [];  for (const key in obj) {    keyValuePairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));  }  return keyValuePairs.join('&');}

... and use it like this:

const queryString = objToQueryString({    key1: 'somevalue',    key2: someVariable,});fetch(`https://example.com/foo?${queryString}`);
answeredDec 24, 2017 at 17:26
Mark Amery's user avatar

Comments

5

Here's an es6 approach

const getQueryString = (queries) => {    return Object.keys(queries).reduce((result, key) => {        return [...result, `${encodeURIComponent(key)}=${encodeURIComponent(queries[key])}`]    }, []).join('&');};

Here we're taking in a queries object in the shape ofkey: paramWe iterate and reduce through the keys of this object, building an array of encoded query strings.Lastly we do a join and return this attachable query string.

answeredMar 18, 2020 at 23:59
flashpaper's user avatar

2 Comments

Although we both know that the code is quite straight forward, still add some explanation is preferred for an answer.
example: const data = {city:'Amman', country:'Jordan', month: 7, annual: false}; fetch(http://api.aladhan.com/v1/calendarByCity?${getQueryString(data)}, { method: "GET" })
4

I did a small riff onMark Amery's answer that will pass Airbnb's eslint definitions since many teams seem to have that requirement these days.

function objToQueryString(obj) {  const keyValuePairs = [];  for (let i = 0; i < Object.keys(obj).length; i += 1) {    keyValuePairs.push(`${encodeURIComponent(Object.keys(obj)[i])}=${encodeURIComponent(Object.values(obj)[i])}`);  }  return keyValuePairs.join('&');}
answeredNov 1, 2018 at 21:03
ZardozSpeaks's user avatar

Comments

2

Yes you should, there are a few classes in JS, that can help you a handy one ishttps://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

e.g. if you had the params in a javascript object say

let params = {one: 'one', two: 'two'}

you could say this function

let queryString = new URLSearchParams()for(let key in params){  if(!params.hasOwnkey())continue  queryString.append(key, params[key])}

then you can get your nicely formatted query string by saying

queryString.toString()
answeredJan 20, 2017 at 17:22
kamikazeOvrld's user avatar

2 Comments

-1;URLSearchParams doesn't exist in React Native. The only way to use it is via a polyfill, and this answer doesn't mention that.
I think this polyfill is included by default with React Native viawhatwg-fetch soURLSearchParams should be safe to use, at least as of React Native 0.59.
2

My simple function to handle this:

/** * Get query string * * @param   {*}   query   query object (any object that Object.entries() can handle) * @returns {string}      query string */function querystring(query = {}) {  // get array of key value pairs ([[k1, v1], [k2, v2]])  const qs = Object.entries(query)    // filter pairs with undefined value    .filter(pair => pair[1] !== undefined)    // encode keys and values, remove the value if it is null, but leave the key    .map(pair => pair.filter(i => i !== null).map(encodeURIComponent).join('='))    .join('&');  return qs && '?' + qs;}querystring({one: '#@$code', two: undefined, three: null, four: 100, 'fi##@ve': 'text'});// "?one=%23%40%24code&three&four=100&fi%23%23%40ve=text"querystring({});// ""querystring('one')// "?0=o&1=n&2=e"querystring(['one', 2, null, undefined]);// "?0=one&1=2&2" (edited)
answeredNov 29, 2018 at 9:56
Yevhen S's user avatar

Comments

0

The accepted answer works, but if you have more params than one it doesn't generalize. I suggest the following approach, which also handles array parameters:

let route = 'http://test.url.com/offices/search';if (method == 'GET' && params) {  const query = Object.keys(params)    .map((k) => {      if (Array.isArray(params[k])) {        return params[k]          .map((val) => `${encodeURIComponent(k)}[]=${encodeURIComponent(val)}`)          .join('&');      }      return `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`;    })    .join('&');  route += `?${query}`;}
ggorlen's user avatar
ggorlen
59.3k8 gold badges119 silver badges173 bronze badges
answeredDec 8, 2017 at 8:46
iuliu.net's user avatar

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy 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.