5 Ways to Fetch API Data in React.js
Zahab Kakar
Posted on September 24, 2021
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));
}, []);
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
- import it to your project
import axios from "axios"
- Here is the syntax
useEffect(() => {
axios.get("https://randomuser.me/api/")
.then((response) => console.log(response.data));
}, []);
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));
}
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
javascript
- import it to your project
import useFetch from "react-fetch-hook"
- Here is how we can use it
const {data} = useFetch("https://randomuser.me/api/");
console.log(data);
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
- import it to your project
import { QueryClient, QueryClientProvider, useQuery } from 'react-query'
- 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>
)
}
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 :)
Posted on September 24, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
May 26, 2024