Loading...

Reactjs fetch API example

Reactjs fetch API example

Hey readers, In this article we will be learning about how to fetch data from an API using React js as well as an example of the same. In case you don’t know what is React js, I would recommend you to check React js blog on codedamn. Here I’ll just give you a glimpse of what is React js.

What is React js?

React js is an easy, structured, and flexible library of JavaScript used for building the UI (User Interface) or frontend of a web application or mobile application. 

It is an open-source library developed by Meta (previously Facebook) to build complex large-scale applications easily with the use of reusable components and elements. 

What is an API?

It is an abbreviation of Application Programming Interface which acts as an interface between two applications while talking to each other. In other words, the API acts as a messenger that delivers your request to the server or provider and finally sends back the response to us. 

Fetching API example

In this article, we will demonstrate how to fetch a piece of information from an API to our end application. For getting data or information, we will be using API http://jsonplaceholder.typicode.com/users where we will retrieve information like ‘id’, ‘name’, ‘username’, and ‘email’ from the API and show it to the user in our application by using components in React js. 

Below are the steps to fetch data from an API using React:

  • Create a React project using the following command: npm create-react-app APP_NAME
  • Go to your folder using the following command: cd APP_NAME
  • If file App.js already exists then write the code given below or just make a new file App.js and then write the code.
import React from "react";
import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
DataisLoaded: false
};
}
componentDidMount() {
fetch(
"https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((json) => {
this.setState({
items: json,
DataisLoaded: true
});
})
}
render() {
const { DataisLoaded, items } = this.state;
if (!DataisLoaded) return <div>
<h1> Pleses wait some time.... </h1> </div> ;
return (
<div className = "App">
<h1> Fetch data from an api in react </h1> {
items.map((item) => (
<ol key = { item.id } >
User_Name: { item.username },
Full_Name: { item.name },
User_Email: { item.email }
</ol>
))
}
</div>
);
}
}
export default App;
  • In the terminal write the following command to start your server: npm start

Go to http://localhost:3000/ in your browser and you can now see your application has all the data fetched from an API to your application’s frontend.

However, this was done using the fetch() function. Similarly, there are multiple ways in which you can fetch data from API in React by using various libraries. 

Fetch data using Axios

It is similar to fetch, the only change is that we don’t need to convert the data into a JSON object and use .then, instead we can directly fetch the data and return it as a JSON object. It has a shorter syntax and includes many tools and features. Here is how you can use fetch data using Axios.

Install Axios using the following command: npm install axios

Run the code given below

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

Fetching data using async/await 

It enables us to remove the .then() function and make asynchronous callbacks. 

Below is the code for fetching data using async/await

useEffect(() => {
getData()
}, []);
async function getData() {
const response = await fetch('/movies');
const result = await response.json();
console.log(result.data));
}

Fetching data with custom hooks

Using useEffect() repeatedly can be tedious and makes code length look longer. Therefore, custom hook is a more efficient and clear way of fetching data due to its short syntax and library react-fetch-hook.

To use it, first install it using the following command: npm install react-fetch-hook

Run the code given below

import useFetch from "react-fetch-hook"
const {data} = useFetch("https://randomuser.me/api/");
console.log(data);

This is how by using a custom hook, you can fetch data by just using a few lines.

Fetching data using React query library

Although a custom hook must be a great way to fetch data, the query is more efficient than the hook. Along with clear syntax, it provides a state management tool to control how and when the data should be fetched.

To use it, run the command line given: npm install react-query

Below is the code for fetching data using React query library

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://jsonplaceholder.typicode.com/users')
.then(response =>
response.json()
)
)
if (isLoading) return 'Loading.'
if (error) return 'Error has occurred: ' + error.message
return (
<div>
<h1>{data.name}</h1>
<p>{data.email}</p>
<p>{data.address}</p>
</div>
)
}

Conclusion

This was all about fetching API using React js. Check out the latest tech courses on codedamn. You can also use their playground which has a built-in environment for all development programming languages specially made for practicing without having to build an environment. Also if you have any queries, do let us know in the comment box, and don’t forget to join codedamn’s developer community.

Sharing is caring

Did you like what Agam singh, Aman Ahmed Siddiqui, Aman Chopra, Aman, Amol Shelke, Anas Khan, Anirudh Panda, Ankur Balwada, Anshul Soni, Arif Shaikh, wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far