How to create a common API handler in react js or react native?

Ever thought of creating a common API handler function in react js or react native which will handle all the API requests coming from components, actions or redux sagas, etc.

Even I have faced issues in handling multiple API requests coming from various places which becomes cumbersome at some time, writing API calls in multiple places is not a standard. All the common API request parameters or methods should be placed at one place which becomes easier to manage when the application grows a larger scale.

Benefits of writing a common API handler

  • Single place to manage
  • Less coding conflicts
  • Standard way

Let's see how we can create a common method for API requests :

Create an api.js file in the helpers' folder, if the helpers folder does not exist create one inside your main project directory.

Install the Axios plugin and import axios in the api.js file.

Add the below code in the api.js file

  import axios from 'axios'

  let bearerToken

  export default async function request(method, url, params, noauth) {
  const body = method === 'get' ? 'params' : 'data'

  const config = {
      method,
      url,
      baseURL: 'API_URL_HERE',
      [body]: params || {}
  }
  if (!noauth) {
      if (!bearerToken) {
             const jwt = // get the jwt token
             if (jwt) bearerToken = 'Bearer ' + jwt
          }
           if(bearerToken) {
           config.headers = {
             Authorization: bearerToken
           }
      }
  }
  // console.log(axios)

     return axios.request(config)
   }

Replace API_URL_HERE with your base API URL like www.google.com

Now we need to call this API handler in some place, that place can be anywhere where you want to manage your API calls and its returning data.

Let's see how to call the API handler in the redux-saga for login functionality

import api from '../../helpers/api'


function loginToApi() {
    return api('post','/login', {email:'testuser', password:'testtest'}, true)
    .then(logIt)
    .catch(catchIt)
}

The /login parameter in the above function is the next part of the api url, now the whole api url will be www.google.com/login

The above function can be called in the generator function like below:

import { call, take } from 'redux-saga/effects'
import { types } from '../modules/identity'


 export function* identitySaga() {
  while (true) {
  const { credentials } = yield take(types.login)
  try {
      const response = yield call(loginToApi, credentials)

    if(response){
            console.log("Manage your response here")
      }
  }
      catch (err) {
      console.log(err)
      }
    }
 }

The API handler can be used any other place also, it depends on you how you want to use it.

In this article, you have got to know how to create a common API handler which reduces a lot of code and gives more readability. If you find any kind issue please do inform.