ReactJS: ReactJS is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application. It is maintained by Facebook.
API: API is an abbreviation for Application Programming Interface which is a collection of communication protocols and subroutines used by various programs to communicate between them. A programmer can make use of various API tools to make its program easier and simpler. Also, an API facilitates programmers with an efficient way to develop their software programs. In this article, we will know how we fetch the data from API (Application Programming Interface). For the data, we have used the API endpoint from
http://jsonplaceholder.typicode.com/users
Approach: In this article, we will know how we fetch the data from API (Application Programming Interface). For the data, we have used the API endpoint from https://jsonplaceholder.typicode.com/todos we have created the component in App.js. From the API we have targeted “userId”, “id”, “title”, and “completed” and fetch the data from API endpoints.
Below is the stepwise implementation of how we fetch the data from an API using 3 different ways in react.
Step 1: Create React Project
npx create-react-app apis
Step 2: Change your directory and enter your main folder charting as
cd apis
Step 3: Write code in App.js to fetch data from API.
Project Structure: It will look the following.
Now we have 3 ways to fetch data from an API
1. fetch method: The fetch() method in JavaScript is used to request to the server and load the information in the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise.
App.js
Javascript
import { useEffect } from "react" ; function App() { useEffect(() => { .then(response => response.json()) .then(json => console.log(json)) }, []); return ( <div> Different ways to fetch Data </div> ); } export default App; |
Step to run the application: Open the terminal and type the following command.
npm start
Output: Now open localhost:300 and in the console, the data is fetched.
2. Axios Package: Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on Github. It can be imported in plain Javascript or with any library accordingly.
To install Axios write the following command
npm i axios
App.js
Javascript
import { useEffect } from "react" ; import axios from "axios" function App() { useEffect(() => { .then((response) => console.log(response.data)); }, []); return ( <div> Different ways to fetch Data </div> ); } export default App; |
Step to run the application: Open the terminal and type the following command.
npm start
Output: Now open localhost:300 and in the console, the data is fetched.
3. Async-Await: This is the preferred way of fetching the data from an API.
Async: It simply allows us to write promise-based code as if it was synchronous and it checks that we are not breaking the execution thread. It operates asynchronously via the event loop. Async functions will always return a value.
Await: Await function is used to wait for the promise. It could be used within the async block only. It makes the code wait until the promise returns a result. It is used to prevent call-back hell and we can use it with Axios rather than the fetch method as Axios makes our code look cleaner and also makes it shorter(as we don’t need to convert to JSON format).
App.js
Javascript
import { useEffect } from "react" ; import axios from "axios" function App() { useEffect(() => { (async () => { try { const result = await axios.get( console.log(result.data); } catch (error) { console.error(error); } })() }) return ( <div > Different ways to fetch Data </div> ); } export default App; |
Step to run the application: Open the terminal and type the following command.
npm start
Output: Now open localhost:300 and in the console, the data is fetched.
4. Using Custom hook: Create one file(useFetch.js) for your custom hook which returns the state of important parameters like data, loading, and error. App.js file will import this hook
Now write the following code:
useFetch.js
Javascript
import { useEffect, useState } from "react" ; import axios from "axios" ; function useFetch(url) { const [data, setData] = useState( "" ); const [loading, setLoading] = useState( false ); const [error, setError] = useState( "" ); useEffect(() => { setLoading( true ); axios .get(url) .then((response) => { setData(response.data); }) . catch ((err) => { setError(err); }) .finally(() => { setLoading( false ); }); }, [url]); const refetch = () => { setLoading( true ); axios .get(url) .then((response) => { setData(response.data); }) . catch ((err) => { setError(err); }) .finally(() => { setLoading( false ); }); }; return { data, loading, error, refetch }; } export default useFetch; |
Import the useFetch hook and pass the URL of the API endpoint from where you want to fetch data.
App.js
Javascript
import { useEffect } from "react" ; import axios from "axios" function App() { const { data: dataInfo, loading, error, refetch } = useFetch( https: //jsonplaceholder.typicode.com/todos ); return ( <div > Different ways to fetch data {console.log(data)} </div> ); } export default App; |
Step to run the application: Open the terminal and type the following command.
npm start
Output: Now open localhost:300 and in the console, the data is fetched.