Making AJAX calls with Fetch in React Native

I've been playing around with React Native a bit and found myself wishing for more documentation, especially with Fetch. While MDN has a treasure trove of information, a lot of constructors for it (such as Request, Response, and Header) are not available in React Native (at least as of the most current build, v0.4.4).

After spending a good amount of time grinding at it, I discovered how easy it can be:

fetch('API_ENDPOINT', OBJECT)
  .then(function(res) {
    return res.json();
   })
  .then(function(resJson) {
    return resJson;
   })

The object passed in at the second parameter for fetch is really important. Let's take a look at it:

var obj = {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Origin': '',
    'Host': 'api.producthunt.com'
  },
  body: JSON.stringify({
    'client_id': '(API KEY)',
    'client_secret': '(API SECRET)',
    'grant_type': 'client_credentials'
  })

As you can see, fetch accepts an endpoint as its first parameter followed by an optional object as its second. This object allows you to define the AJAX method (i.e. 'GET' or 'POST'), any headers you're passing in (as an object), and the body (as stringified JSON).

I hope this has been helpful in any way at all!

P.S. I wrote a book on React Native development! It's titled React Native By Example and is available for purchase on Amazon. It's a fantastic resource for React Native development and if you're interested in leveling up your skills, I strongly recommend checking it out!

Show Comments