GET request using axios with React Hooks
Today we’ll show you how to integrate GET request using axios with React Hooks.
We had created an article to call an API using the window.fetch
method.
Axios is the promise based client for frontend and backend applications. Axios offers may more features compare to fetch
.
In this article, we will create the following example using the axios package.
Demo Application
Table of Contents: GET request using axios
1. Installing axios
Run the following command to install the axios with npm or yarn CLI.
npm CLI: npm install axios
yarn CLI: yarn install axios
2. Syntax of the GET request using axios
The following syntax will be used to call GET API using axios.
1 2 3 4 5 6 7 | axios.get("https://reqres.in/api/users") .then(response => { console.log("Status: ", response.status); console.log("Data: ", response.data); }).catch(error => { console.error('Something went wrong!', error); }); |
In the above code, we have used the get
method of the axios and pass the URL in the first parameter.
3. GET request with HTTP headers
We can use the second parameter to pass the HTTP headers. Look at the following code where we are passing the Authorization
and Custom-Header
along with the same request.
1 2 3 4 5 6 7 8 9 10 11 | const headers = { 'Authorization': 'Bearer my-auth-token', 'Custom-Header': 'xxxx-xxxx-xxxx-xxxx' }; axios.get("https://reqres.in/api/users", { headers }) .then(response => { console.log("Status: ", response.status); console.log("Data: ", response.data); }).catch(error => { console.error('Something went wrong!', error); }); |
4. Example
Here, we will use the bootstrap package to design the page where we will get the list of the data on page load.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | import React, { useEffect, useState } from 'react'; import axios from "axios"; import 'bootstrap/dist/css/bootstrap.min.css'; function App() { const [userList, setUserList] = useState([]); useEffect(() => { axios.get('https://reqres.in/api/users').then(res => { setUserList(res.data.data); }); }, []); return ( <div className="container-fluid p-3"> <h5 className="d-inline-block">GET request using axios with React Hooks - <a href="https://www.cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h5> <table class="table table-sm mt-3"> <thead class="thead-dark"> <th>First Name</th> <th>Last Name</th> <th>Email</th> <th>Avatar</th> </thead> <tbody> {userList.map(x => <tr> <td>{x.first_name}</td> <td>{x.last_name}</td> <td>{x.email}</td> <td><img src={x.avatar} width="50" height="50" /></td> </tr>)} {userList.length == 0 && <tr> <td className="text-center" colSpan="4"> <b>No data found to display.</b> </td> </tr>} </tbody> </table> </div> ); } export default App; |
Run the above file and check the output in the browser.
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂