GET with query string with Fetch in React Native

Guy picture Guy · May 14, 2016 · Viewed 83.5k times · Source

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.

Answer

Ben Clayton picture Ben Clayton · May 14, 2016

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