GET with query string with Fetch in React Native


GET with query string with Fetch in React Native



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 the docs.





Possible duplicate of Setting query string using Fetch GET request
– Hirurg103
Jun 30 at 14:29




4 Answers
4



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,
body:body
})





Thank you, took me forever to realize they were backticks instead of single quotes
– Chris Gong
Jun 8 at 14:56



Just substitute values into the URL like this:


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



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 that someVariable definitely doesn't contain any &, =, or other special characters.


someVariable


&


=



If you were using fetch outside of React Native, you'd have the option of encoding query string parameters using URLSearchParams. However, React Native does not support URLSearchParams. Instead, use encodeURIComponent.


fetch


URLSearchParams


URLSearchParams


encodeURIComponent



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}`);



Yes you should, there are a few classes in JS, that can help you a handy one is https://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()





-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.
– Mark Amery
Dec 24 '17 at 16:57


URLSearchParams



Accepted answer works.. but if you have more params you're screwed. I suggest the following approach:


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}`;
}



EDIT: Updated answer to work with arrays as well





This is potentially reasonable but yikes, the formatting of that codeblock is painful.
– Mark Amery
Dec 24 '17 at 17:00






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to input without newline? (Python)

C++ thread error: no type named ‘type’ MINGW

Analog for TagView in flutter