Create A custom Http Service Provider in React

Create A custom Http Service Provider in React

Subscribe to my newsletter and never miss my upcoming articles

Hey there! This post is for my front-end app while building Codemarka and a good practice I adopted and you should too.

THE PROBLEM: On my server, I've got routes that are protected. To access them you'll need to provide an auth token in the request header. On my react app, i could easily do this with Axios or fetch everywhere I needed to make an API call.

After a while, this seemed like i was repeating myself everywhere because i get to write the same code with a difference in URL and data passed as payload. Also, attaching the token was somehow painful for me as much code was needed to retrieve it from where it was stored.

So the real issue here was repeating the same code in multiple places.

MY FIX: Creating an HTTP Service provider module was the best thing for me. How does this work?? A simple javascript file exporting a function which returns an object of various http methods i would make use of in my app. Let's dive into the code.

import Axios from 'axios';

export default function HttpService(){
  const token = 'fake.ass.token'

  const headers = {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${ token }`
  }

  return {
    GET: function(url){
        return Axios.get(url,{headers}).then(response => {
            return response;
        }).catch(err => {
           throw err;
        });
    },
    POST: function(url,data){
      return Axios.post(url,data,{headers}).then(response => {
        return response;
      }).catch(err => {
        throw err;
      })
    }
  }  
}

We just have two methods in there, but could be more. Let's look at how to make use of this function. In the file where you need this service, find a way to import it, ensure to do the initial instantiation and you get the available methods exposed. Sample usage below.

import React from 'react'
import http from '../services/http';

function FetchLatestRooms({room}){
     React.useEffect(() => {
       http().GET(`${ API.FETCH_ROOMS}${ room }`).then(response => {
            setState({...state, rooms: response.data.message});
        })
    },[])
}

We basically just have a functional component to fetch rooms from the server in a useEffect hook that runs just once on mount. A very simple and neat way of making API calls where authorization is required, I will never have to worry about setting tokens, they get attached automatically. You could also do a lot of custom configuration in here too.

Let me know what you think about this below in the comment section.

 
Share this