React Native Http Interceptor

Have you considered axios if you are trying to intercept only xhr? I am using axios interceptors - https://www.npmjs.com/package/axios and so far it seems to work.

Here is the sample code

import axios from 'axios';
import promise from 'promise';

// Add a request interceptor 
var axiosInstance = axios.create();

axiosInstance.interceptors.request.use(function (config) {
  // Do something before request is sent 
  //If the header does not contain the token and the url not public, redirect to login  
  var accessToken = getAccessTokenFromCookies();

  //if token is found add it to the header
  if (accessToken) {
    if (config.method !== 'OPTIONS') {
          config.headers.authorization = accessToken;
        }
  }
  return config;
}, function (error) {
   // Do something with request error 
   return promise.reject(error);
});

export default axiosInstance;

and then import this axiosInstance where ever you want to make xhr calls


I'm not sure if I'm understanding this question correctly, or if your looking for more magic, but it sounds like you just want a wrapper to the XMLHttpRequest (or fetch API). Wrap it in a class or a function and you can do whatever you want, whenever you want. Here's an example of an xhr wrapped in a promise:

function request(url, method = "GET") {
  const xhr = new XMLHttpRequest();

  // Do whatever you want to the xhr... add headers etc

  return new Promise((res, rej) => {
    xhr.open(method, url);
    xhr.onload = () => {
      // Do whatever you want on load...
      if (xhr.status !== 200) {
        return rej("Upload failed. Response code:" + xhr.status);
      }
      return res(xhr.responseText);
    };
    xhr.send();
  });
}

Then you can just use that whenever you want to do HTTP calls...

request("http://blah.com")
  .then(data => console.log(`got data: ${data}`))
  .catch(e => console.error(`error: ${e}`));