Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
In this article, we are going to learn about HTTP Get Method in React JS. Basically, we need to use HTTP requests to fetch and use APIs in general, so in many react applications we make use of these HTTP methods to get data from APIs. So learning about HTTP methods are essential. The five commonplace HTTP request methods are GET
, PUT
, POST
, PATCH
, and DELETE
. These methods allow us to perform standard CRUD operations.
Today we will see about HTTP Get method in react JS, So let’s jump into it.
Get
method is an HTTP request method which aims to get resources from a server (here specifically API). It is a basic method which is going to help us to get data from server.
We can use Basically two methods to work with get method: (1)fetch, (2)axios.
The fetch() method is one of the common method to use in the ReactJS. In react, the fetch method takes one mandatory argument, which is here a URL, or an API URL. Also, its default value is Get
, so we don’t need to mention it manually. Remember, you can use this fetch method directly, without installing any other packages.
Fetch promises to give data, so that we can handle then() method and catch() method to work with the data. Here response.json()
is used to convert raw data to JSON formatted data.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// Do something with the data
})
.catch(error => {
// Handle the error
});
Here is a basic example for the fetch method, As you can see we called the API in useEffect which aims to call the API before application render. Also, we used a useState to store data after every successful call. To store data from API call, we ideally use useState hooks.
import { useState, useEffect } from 'react';
const App = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => res.json())
.then((data) => {
console.log(data);
setPosts(data);
})
.catch((err) => {
console.log(err.message);
});
}, []);
return (
// ... consume here
);
};
Axios is another way to work with get
method, It looks cleaner than fetch() method, right? Axios is a promise-based HTTP client library that makes it simple to send asynchronous HTTP requests to REST endpoints.
Axios is an external library, or you can say external package. So you need to install it in your React application using this line of code in terminal or cmd.
npm install axios
To use get method in axios, we use axios.get()
which takes a mandatory argument (URL). Axios is pretty different than fetch, because axios provides more powerful and flexible APIs than fetch method.
import axios from 'axios';
axios.get('https://api.example.com/data')
.then(response => {
// Do something with the data
})
.catch(error => {
// Handle the error
});
To use get
a method in a functional component, we should call the APIs in the useEffect hook, ideally.
import { useState, useEffect } from 'react';
const App = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => res.json())
.then((data) => {
console.log(data);
setPosts(data);
})
.catch((err) => {
console.log(err.message);
});
}, []);
return (
// ... consume here
);
};
Also, to use get
method in the class component, we make API calls in the componentDidMount()
method, ideally. Fetch and axios methods will be remained same in class components.
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
posts: [],
};
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((data) => this.setState({ posts: data }))
.catch((error) => console.log(error));
}
render() {
const { posts } = this.state;
return (
// ...
);
}
}
Async/await method is not a different way to get data from API, but you can say it is the way to use fetch and axios method. Here are basic examples:
import React, { useState, useEffect } from 'react';
function ExampleComponent() {
const [data, setData] = useState(null);
useEffect(() => {
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
setData(data);
} catch (error) {
console.error(error);
}
}
fetchData();
}, []);
return (
<div>
{data ? <p>{data.example}</p> : <p>Loading...</p>}
</div>
);
}
export default ExampleComponent;
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function ExampleComponent() {
const [data, setData] = useState(null);
useEffect(() => {
async function fetchData() {
try {
const response = await axios.get('https://api.example.com/data');
setData(response.data);
} catch (error) {
console.error(error);
}
}
fetchData();
}, []);
return (
<div>
{data ? <p>{data.example}</p> : <p>Loading...</p>}
</div>
);
}
export default ExampleComponent;
You may Also like: