React Hooks for Axios GET and POST

Izhan Yameen
3 min readSep 19, 2020

In this article we are building two custom hooks of react to get and post data from api.

Before we get started I assume that you have basic understanding of React and useState and useEffect hooks. Also we are using axios for HTTP GET and POST requests but you can use other libraries also.

ok now go ahead and make a new react project at your desired location and change your directory into the newly created project as shown in below commands

npx create-react-app react-axios-hooks

after the project creation is complete change the working directory in your terminal

cd react-axios-hooks

after you created your project it’s time to install axios from npm. Type below command in terminal

npm install axios --save

after the axios installation is complete go ahead and start your project

npm start

It’s time to jump into coding. Open your project inside any editor you like. I am using VS-Code.

Get Hook

Inside your src folder create a new file named AxiosHooks.js Inside this file add the following code

import { useState, useEffect } from "react";
import axios from "axios";
export function useAxiosGet(url) {
const [data, setData] = useState();
useEffect(() => {
axios
.get(url)
.then((response) => setData(response.data))
.catch((error) => console.error(error));
}, [url]);
return data;
}

In the above code we are declaring a function named useAxiosGet this is a custom hook that will make our get request. This function takes a url as a parameter and return fetched data. You can see that there is an useEffect hook in this function. When you use this hook in your code the useEffect inside it will fire off only once. Note that we are passing url inside dependency array of useEffect hook this will make sure that if the given url is changed it has to re-fetch the data.

to use our get hook open App.js file or any other component where you want to fetch data and use it as shown below

import React from 'react';
import { useAxiosGet } from './AxiosHooks';
// dummy url to fetch data from
const url = 'https://jsonplaceholder.typicode.com/todos/1';
function App() {
const data = useAxiosGet(url);
// show loading before the data is fetched
return !data ? <h1>Loading...</h1> : (
<pre>
{JSON.stringify(data, null, 2)}
</pre>
);
}
export default App;

After that you you can see the fetched data in your application. We are using jsonplaceholder api to fetch our data you can replace the url to your own api end point

Post Hook

Now our get hook is ready it’s time to code our post hook. Go ahead and open AxiosHooks.js file and add below function to it

export function useAxiosPost() {
const [input, setInput] = useState({
data: null,
url: null,
callback: null
});
useEffect(() => {
const postData = () => {
axios
.post(input.url, input.data)
.then(res => input.callback(res.data))
.catch(err => console.error(err));
};

if(input.data && input.url && input.callback) {
postData();
}
else {
console.log('Invalid arguments provided to post method');
}
}, [input]);
const post = (url, data, callback) => {
setInput({ url, data, callback });
}
return post;
}

In the above code we are creating a custom hook named useAxiosPost. This custom hook returns a function named post which we can use in our component. The post function expects some arguments that are url on which the data will be posted, data object and a success callback which will run after success posting of our data.

When post function is called it sets the input state of our function which will eventually triggers our useEffect hook because we are providing input in our dependency array of our useEffect.

The implementation of useAxiosPost hook is as follows

import React from 'react';
import { useAxiosPost } from './AxiosHooks';
// dummy url for posting data
const url = "https://jsonplaceholder.typicode.com/todos";
function App() {
const post = useAxiosPost();
const handlePostData = () => {
post(
url,
{
userId: 1,
id: 1,
title: "delectus aut autem",
completed: false
},
(data) => {
console.log(data);
}
);
};
return (
<div>
<button onClick={handlePostData}>Post Data</button>
</div>
);
}
export default App;

That’s it we’re done…. !

--

--