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 :)
Top comments (8)
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.
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. :)
Awesome, I would prefer the react built in function👌🏼
Thank you Paul :)
Like your articles, you got a follow of mine :)
Thank you for your support Paul!
Hope you find my articles helpful.
Very interesting, thanks for sharing
Glad you liked it, Amusan :)