Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 361
Guy Avatar asked May 14 '16 18:05

Guy


People also ask

How do I add a query to fetch?

keys(query). length; for(let key in query) { fetchLink += key+'='+query[key]; fetchLink += (count < queryLength) ? '&' : ''; count++; } } // link becomes: 'http://myapi.com/orders?order_id=1' // Then, use fetch as in MDN and simply pass this fetchLink as the url. }


2 Answers

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,    }) 
like image 113
Ben Clayton Avatar answered Oct 06 '22 02:10

Ben Clayton


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

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.

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}`); 
like image 33
Mark Amery Avatar answered Oct 06 '22 01:10

Mark Amery