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
Let's eat now shall we??:
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
}
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'
}
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
}
})
}
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
}
})
}
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'
}
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
}
})
}
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>
);
}
The final result looks like this, you can go ahead to style it yourself for finishing touches.
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)
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
This is clean......👌💯
Well done boss.
This article just cleared my doubts 🔥🔥
Nice write-up!
it was helpful thanks for sharing with us
also we can use react-query . it manage all states that we need for api calls
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..
Nice work 👍🏽… let’s see how this works with interceptors for error and token management 🙌🏽
Alright boss, I'll learn about that. Thank you for the feedback
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.