GET Request in React.js using Fetch Example and Tutorials

    Oct 21, 2019       by Pankaj Kumar

For making application dynamic we need to make request to server to get the data from server, For that we have different options in React.js library like Fetch, Axios etc...

In this article, We will see example for making GET Request in React.js application using Fetch.The Fetch API is a modern interface that allows you to make HTTP requests to servers from web browsers. We don't need to import any extra packages to use Fetch because if comes inbuilt with the browser.

 

Simple GET Request using Fetch in class base component

Here, we will make a GET Request to the server of jsonplaceholder to get the record detail.

 

 
componentDidMount() {
  // GET detail
const header = {}
  fetch('https://jsonplaceholder.typicode.com/todos/1',header)
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(error => {console.log(error)})
}
 

 

GET Request in Class-based component using async/await

 

 
async componentDidMount() {
  // GET request using fetch with async/await
  const header = {}
  const response = await fetch('https://jsonplaceholder.typicode.com/todos/1',header);
  const data = await response.json();
  console.log(data);
}
 

 

 

Using Fetch for GET Request in React Hooks App

The above example was for making GET Request in class based Reactjs application. In this we will see how to make GET Request in React Hooks Application. Here we will use useEffect in place of componentDidMound lifecycle.

 

 
useEffect(() => {
// GET request in useEffect React hook
const header = {}
fetch('https://jsonplaceholder.typicode.com/todos/1',header)
.then(response => response.json())
.then(json => console.log(json))
.catch(error => {console.log(error)})
 
}, []);
 

 

Conclusion

So in this article, We learn about the different ways to make GET Request in React.js application using Fetch. You can also find other demos of React.js Sample Projects here to start working on enterprise-level applications.

That’s all for now.

Let me know your thoughts over email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share it with your friends.


WHAT'S NEW

Find other similar Articles here: