DEV Community

Cover image for 5 Ways to Fetch API Data in React.js
Zahab Kakar
Zahab Kakar

Posted on • Originally published at zahab.tech

5 Ways to Fetch API Data in React.js

This article is a reference guide to strengthen your skills as a React developer and for job interviews.

Introduction:

React is one of the JavaScript libraries for building user interfaces or UI components. Many react projects require interaction with the outside world data. For example, when we want to create a weather application, we need accurate data which should change dynamically. We can access this data by fetching API. In this article, we will explore different ways that you can fetch data in react.js.

Ways of Fetching Data

1. Fetch Data in React Using the Fetch API

Fetch API is available in modern browsers (window. fetch) and allows us to make requests using JavaScript promises. We can use the fetch() method to get the data. To make a simple GET request with fetch, we just need to include the URL endpoint to which we want to make our request. Here is an example of how we can use it.

useEffect(() => {
  fetch("https://randomuser.me/api/")
  .then((response) => response.json())
  .then((data) => console.log(data));
  }, []);

Enter fullscreen mode Exit fullscreen mode

The first .then is for returning a JSON object of the result and the second one is for printing at the console.

2. Fetch Data in React Using Axios

This is used to make requests with React using axios. It is the same as the Fetch, however, in this approach, we don't need to convert the data to JSON and use the first .then, axios directly fetch data and return the JSON object. Axios is the shorter syntax that allows us to cut down on our code and it includes a lot of tools and features which Fetch does not have in its API.
Here is how to use axios.

  • first installing axios
$ npm install axios
        or
$ yarn add axios
Enter fullscreen mode Exit fullscreen mode
  • import it to your project
import axios from "axios"

Enter fullscreen mode Exit fullscreen mode
  • Here is the syntax
useEffect(() => {
  axios.get("https://randomuser.me/api/")
      .then((response) => console.log(response.data));
  }, []);

Enter fullscreen mode Exit fullscreen mode

3. Fetch Data in React Using async / await syntax

Async / await enables us to remove our .then() callbacks and simply get back our asynchronously resolved data. Remember, We can not make an async function inside the useEffect.

useEffect(() => {
      getData()
  }, []);

async function getData() {
  const response = await fetch('/movies');
  const result = await response.json();
  console.log(result.data));

}
Enter fullscreen mode Exit fullscreen mode

4. Fetching Data with Custom Hook

It is always better to have a clean code and short syntax, and you might realize that using useEffect over and over again is tedious, even sometimes it confuses many developers. Here we have a more clear way to fetch data. Using a third library **react-fetch-hook **allows us to fetch data and cut down on our reused code.

  • First, we need to install *react-fetch-hook *
$ npm install react-fetch-hook
             or
$ yarn add react-fetch-hook


Enter fullscreen mode Exit fullscreen mode


javascript

  • import it to your project
import useFetch from "react-fetch-hook"

Enter fullscreen mode Exit fullscreen mode
  • Here is how we can use it
const {data} = useFetch("https://randomuser.me/api/");
console.log(data);

Enter fullscreen mode Exit fullscreen mode

5. Fetch Data in React Using the React Query Library

You might think that using custom hooks is a great approach, Yes! However, React Query takes the fetching with hooks to the next level. React Query not only provide a simple and clear syntax but also deal with state management tools to control when, how and how often our data is fetched.

  • First, install the react query
$ npm i react-query
           or
$ yarn add react-query

Enter fullscreen mode Exit fullscreen mode
  • import it to your project
import { QueryClient, QueryClientProvider, useQuery } from 'react-query'

Enter fullscreen mode Exit fullscreen mode
  • Here is how we can use it
import { QueryClient, QueryClientProvider, useQuery } from 'react-query'

 const queryClient = new QueryClient()

 export default function App() {
   return (
     <QueryClientProvider client={queryClient}>
       <Example />
     </QueryClientProvider>
   )
 }

 function Example() {
   const { isLoading, error, data } = useQuery('nameForYourData', () =>
     fetch('https://api.github.com/repos/tannerlinsley/react-query')
.then(response =>
       response.json()
     )
   )

   if (isLoading) return 'Loading...'

   if (error) return 'An error has occurred: ' + error.message

   return (
     <div>
       <h1>{data.name}</h1>
       <p>{data.description}</p>
       <p>{data.subscribers_count}</p>
     </div>
   )
 }
Enter fullscreen mode Exit fullscreen mode

That's all for fetching data!🎉🎉

Thank you for reading my article, I hope you found this article useful.

Feel free to connect on
Twitter :)

Top comments (8)

Collapse
 
meatboy profile image
Meat Boy • Edited

I would recommend to avoid no 4 and 5 - „little duplication is better than dependency”. Using external lib for trivial tasks doesn’t make your code more readable. Clean code is not about amount of code but rather about readability.

Collapse
 
zahab profile image
Zahab Kakar • Edited

Hey there, thank you so much, for your great explanation. Yes but when some developers see two different ways of mentioning them, which looks complicated and they will confuse, that's y I have mentioned as too different points(If we explore each more in details, they still have some differences).
Yes we should use useState, but the aim of this article was not on fetching and using useState, I was trying to explain how to get data from API, by the way thanks for mentioning these points, i will consider them on my next articles and explain more in details. :)

Collapse
 
pauldunz profile image
Paul Dunz

Awesome, I would prefer the react built in function👌🏼

Collapse
 
zahab profile image
Zahab Kakar

Thank you Paul :)

Collapse
 
pauldunz profile image
Paul Dunz

Like your articles, you got a follow of mine :)

Thread Thread
 
zahab profile image
Zahab Kakar

Thank you for your support Paul!
Hope you find my articles helpful.

Collapse
 
emmanueltoluwanimi profile image
Amusan T. Emmanuel

Very interesting, thanks for sharing

Collapse
 
zahab profile image
Zahab Kakar

Glad you liked it, Amusan :)