DEV Community

Cover image for Cleaner and Better way for calling APIs with Axios in your React-typescript applications
Segun Tuase
Segun Tuase

Posted on

Cleaner and Better way for calling APIs with Axios in your React-typescript applications

I had to make several API calls in a project, but I didn’t want to replicate or keep calling axios every time, I thought I could use a hook, it just didn’t work then I stepped back and realize I could build a helper function that I can import in whenever I need to make API calls. This is going to be a short article, because we just need a very important solution.

Why do we need a helper function

  • It makes the developer write cleaner code

  • It helps with separation of concern

We start by initializing your project and creating react app, the link below explains how to create a React app.
How to create react app

Prerequisites

  • Basic knowledge of React JS

  • Basic knowledge of typescript

in your react app src folder you should have a file called
API.tsx, App.tsx

The package we will be using is Axios - Axios is a Javascript library used to make Http requests in nodeJS or XMLHttpRequests from the browser that also supports the ES6 Promise API.

To install axios with Npm or yarn we use:


yarn add axios
npm i axios -save


Enter fullscreen mode Exit fullscreen mode

Let's eat now shall we??:

shall we meme

In the API.tsx file we will have to import axios and setup the necessary interface



import axios from 'axios'

//interface for the Helper
interface Params {
        baseUrl: string
    headers : any
    method: string
}


Enter fullscreen mode Exit fullscreen mode

Next step will be to set up the config using the Params interface, the config will hold the baseUrl header and method values



//....

//helper config
const config: Params = {
    baseUrl: "https://jsonplaceholder.typicode.com/",
    headers: {
        "Authorization": "",
            },
    method: 'post'
}



Enter fullscreen mode Exit fullscreen mode

Then you create an Asynchronous function that uses axios to make the post request, you add the necessary parameters for axios then you parse out your response and the error message if there’s any. This helps you create a reusable function that you can use to make your API call.



//helper function to be exported
export  const postAPI = async (url: string, data: any): Promise<any> =>{
    return await axios({
        ...postConfig,
        url: `${postConfig.baseUrl}/${url}`,
        data
    }).then ( (response) => {
        console.log(response)
        return {
            status: response.status,
            data: response.data
        }
    }).catch((error) =>{
        console.log(error)
        return {
            status: error.status,
            data: error.response
        }
    })
}


Enter fullscreen mode Exit fullscreen mode

altogether this comes together as



//final code result
import axios from 'axios'

interface Params {
        baseUrl: string
    headers : any
    method: string
}

const postConfig: Params = {
    baseUrl: "https://jsonplaceholder.typicode.com/",
    headers: {
                "Authorization": 
            },
    method: 'post'
}

import axios from 'axios'

interface Params {
        baseUrl: string
    headers : any
    method: string
}

export  const postAPI = async (url: string, data: any): Promise<any> =>{
    return await axios({
        ...postConfig,
        url: `${postConfig.baseUrl}/${url}`,
        data
    }).then ( (response) => {
        console.log(response)
        return {
            status: response.status,
            data: response.data
        }
    }).catch((error) =>{
        console.log(error)
        return {
            status: error.status,
            data: error.response
        }
    })
}


Enter fullscreen mode Exit fullscreen mode

You can also morph it for GET request but the config will be entirely different



//config for get request note that the method as changed to get this is very important
const getConfig : Params = {
    baseUrl: "https://jsonplaceholder.typicode.com",
        headers: {
            "Authorization":
        },
    method: 'get'
}



Enter fullscreen mode Exit fullscreen mode

Your helper function will be



export const getAPI = async (url: string, data: any): Promise<any> =>{
    return await axios({
        ...getConfig,
        url: `${getConfig.baseUrl}/${url}/${data}`,
    }).then ( (response) => {
        console.log(response)
        return {
            status: response.status,
            data: response.data
        }
    }).catch((error) =>{
        console.log(error)
        return {
            status: error.status,
            data: error.response
        }
    })
}


Enter fullscreen mode Exit fullscreen mode

In the last section of the code, we will have to import the helper function into our code and render it out. This is the final part of the task. The first section is the state that holds the data, then we also include a function that that calls the helper function. This function is going to be in the useEffect because we need it to run on render. We then proceed to map out our response in a list. Voilà



//rendering our result to the browser
import {getAPI} from './API' // import the api helper 
import React from "react";
export default function App() {
    const [data, setData] = React.useState([]) // set state to hold the result

        //function below triggers the helper function
         const getData = () => getAPI("posts").then(
      (res) => {
        if(res.status === 200){
          setData(res.data)
          console.log(data) 
        }else{
          console.log(res)
        }
    }
    )

        //this runs the getData trigger function as useEffect
    React.useEffect(()=>{
        getData()
    }, [])

  return (
    <div className="App">
     <ul>
      {
                //maps out our result for rendering
        data.map((x) =>
              <li>
                {x.title}
              </li>
        )
      }
      </ul>
    </div>
  );
}


Enter fullscreen mode Exit fullscreen mode

The final result looks like this, you can go ahead to style it yourself for finishing touches.

Integrating an API with react typescript

If you have further questions on the concept or you have better ideas on approaching the concept please drop a comment or reach out to me.

Thanks for reading

Top comments (8)

Collapse
 
ecyrbe profile image
ecyrbe

Hello,
You should check zodios . It's an http client based on axios where you don't need to write all this boilerplate code to use your API.
It's fully opensource check github

Collapse
 
devcreed profile image
Edun Elijah

This is clean......👌💯

Well done boss.

Collapse
 
ladeomor profile image
Ladeomor

This article just cleared my doubts 🔥🔥
Nice write-up!

Collapse
 
arsalannury profile image
ArsalanNury

it was helpful thanks for sharing with us

also we can use react-query . it manage all states that we need for api calls

Collapse
 
mdrahiem profile image
Rahimuddin

It's nice and simple. Also react-query is a better solution for this problem. But it's not only for querying API calls but for state management too..

Collapse
 
uncoverthefuture profile image
Friday Davis

Nice work 👍🏽… let’s see how this works with interceptors for error and token management 🙌🏽

Collapse
 
tuasegun profile image
Segun Tuase

Alright boss, I'll learn about that. Thank you for the feedback

Collapse
 
thenaman047 profile image
TheNaman047

We can also use axios instance variable for common headers and baseUrl.

Also using axios instance, you can have multiple configs for different base url if you application is using multiple API endpoints then this is really useful.