Create Axios Custom Hooks

Vedant Jain
2 min readFeb 14, 2021

--

Are you using Axios directly in your component to make API calls? Well, you can do it better. It’s always better to create custom hooks for repeated functionalities to make code more modular and re-useable . Always remember if you see repetition in your code then you are doing it wrong!.
I am assuming you you already know how to create custom hooks, if not you can refer to Building Your Own Hooks.

Now let’s have a look at our code and break it down.

We have named our Custom hook as useApi. This hook accepts four parameters, namely

method: defines type of API call i.e POST, GET, DELETE, PUT, PATCH
url: API
dataObject: the data (payload) which you want to send
params: GET api params i.e { ID: 12345 } if the get API is something like /user?ID=12345

Now, let’s see what our hooks do in it’s core.
We have set three states data, loading, error using useState hook.

data: this will receive reponse data after the API call
loading: allows us to maintain a loading state (helps us to show a loader)
error: this will store error object if any error occurs.

Very simple and smooth till here, isn’t it? Now comes the heart of this hook the fetchData function. Let’s try to break this down too.

This function has a try catch finally statement inside it. We try to call the API using our promise based HTTP client Axios. (Asuming, you are familiar with async await). We have passed all our parameters in the Axios function and we wait for this function to return us a response object. When we receive a response from the API we set our data by setData hook. And yes of course we had set loading to true in the starting to represent that the API call has been initiated.

If there was any error then we catch that error and set the error variable using setError hook. And finally we set our loading false.

We have to call our fetchData function inside a lifecycle method. We have to call this function in componentDidMount i.e useEffect hook without any dependencies. This makes sures that this function would be called only once and would avoid infinite re-renders.

And we would happily return { data, loading, error } object !. Pretty simple right?
Using our custom hooks is very easy have a look at the code below

uncomment line 22 to see the data in console and uncomment one line at a time between 17–21 to try out various types of API methods. I am using https://jsonplaceholder.typicode.com/ to test it.
Please note that you have to pass the complete url here unless you haven’t specified the baseUrl in config (which I did in this).
Happy Coding!!

--

--