Writing and Maintaining API layer in React/React Native

If you are starting a new app or already have an app but are not sure how to add API layer to your application then this is the right place. I would like to share my experience on how we currently maintain an API layer. (Remember this is not the only way to do it)

I have seen many projects in React where API’s are included in each component and as the application grows it becomes difficult to keep track of all the endpoints that are getting used.

The components might be infected with fetch requests and might look like the one below:

It might be a pain point initially to figure out how to maintain and structure your API layer, but once done it saves a lot of time in future.

The approach which we have taken helps us to use a single layer for both our React and React Native projects with very minor changes.

Let’s start from the very basic and take a look at the things which are needed for making a network call:

  1. URL which we are supposed to hit
  2. data to be passed
  3. Type of request: GET, POST, PUT etc
  4. Library for making the network call
  5. success/error callbacks
  6. Error tracking

Now, let’s begin by creating the following methods into a separate file

  1. makeRequest: responsible for making network calls
  2. makeGetRequest: responsible for handling GET calls
  3. makePostRequest
  4. makePutRequest

It will look something like this:

You can see that there are more methods in the code than I have listed on top, its normally better idea to follow DRY (Do not Repeat Yourself) principle.

Each of PUT, GET and POST methods above have one common piece which is makeRequest, so that sits in a separate method.

I am using axios which is a fantastic library (has 50k+ stars on Github) and works really well in both react and react native.

I have been using sentry which is yet another great library and is used for tracking errors and works across different platforms.

Now it’s time to move API methods from all of our components into one file (Api.js). In the code sample below you can see how the API methods are getting consumed.

Of course, you can customise the methods according to your project. In my case, I normally pass callback functions in options key and they run post success or failure scenarios.

At last, you can consume API methods in your components something like this:

Now if you also have a React Native project and share a lot of code between your projects, it’s possible to use a single API layer which saves a lot of time and is easier to maintain.

Please let me know in the comment section if you have any doubts/suggestions.

Passionate Web/App Developer @Amazon, #javascript #reactjs #react-native #ruby #rails #elixir