DEV Community

Pankaj Kumar
Pankaj Kumar

Posted on • Updated on

GET Request in React.js using Fetch Example and Tutorials

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)})
}

Enter fullscreen mode Exit fullscreen mode

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);
}

Enter fullscreen mode Exit fullscreen mode

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)})

}, []);

Enter fullscreen mode Exit fullscreen mode

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.

This article is originally posted over jsonworld

Top comments (0)