Cleaner and Better way for calling APIs with Axios in your React-typescript applications
Tags: react, javascript, webdev, beginners
Published: 2022-11-02 14:46:32

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](https://dev.to/ruppysuppy/create-react-app-from-scratch-like-a-pro-de0)

**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:
```bash
yarn add axios
npm i axios -save
```

Let's eat now shall we??:


![shall we meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9bse2l3o7pgn08nc3rtw.jpeg)

In the API.tsx file we will have to import axios and setup the necessary interface
```tsx
import axios from 'axios'
 
//interface for the Helper
interface Params {
		baseUrl: string
    headers : any
    method: string
}
```

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

```tsx
//....

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

```

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.

```tsx
//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
        }
    })
}
```

altogether this comes together as 

```tsx
//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
        }
    })
}
```
You can also morph it for GET request but the config will be entirely different

```tsx
//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'
}

```
Your helper function will be

```tsx
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
        }
    })
}
```

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à

```tsx
//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>
  );
}
```

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


![Integrating an API with react typescript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8uso7dh2fm1e07f1dsnw.jpg)

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