In this post, we are going to discuss Fetch data from API and display it in table React Js using a bootstrap HTML table.
In react, we have two component types, functional component and class component,Functional components are literally JavaScript functions, they return HTML, which describes the UI, for example, a function called “functionalcomp”, which returns, and tag that says “Hello this is a functional Component”.
function functionalcomp() {
return Hello this is a functional Component
}
Class, components, on the other hand, are regular ES6 classes that extend the component class from React the library.they must contain a render method, which in return HTML, for example, class Myclasscomp extends React. Component and the class contain a render method which returns tag that says “Hello this is my class Component”.
class Myclasscomp extends React.Component {
render() {
return Hello this is a my class Component
}
}
In this example, we will discuess both i,e functional component and class component for showing the data .So let’s start.
In this post we will discuss the below points
- Fetch User Data from API and add to table using ReactJS
- Displaying data from fetch API using React Js
- How to fetch API data and show that on table form in react.js
- How to display data from API in react js using fetch API
How to fetch data from API in React js using Fetch API
Step 1 – Create React App
Step 2 – Create components for showing List data
Create two folders called components in the src folder and two components inside that i.e EmployeelistFun.js
and Employeelist.js
Step 3 – Integrate Rest API using fetch() function
React js fetch data from API example
The Fetch API is the latest interface that allows us to make HTTP requests to Rest APIs from the client-side.
If you know about with XMLHttpRequest (XHR) object, then let you know that the Fetch API can perform all the tasks as the XHR object can do.
The fetch() function is available in the global scope that guides the web browser’s client to send a request to a rest URL.
Sending a Request and Reading the Response
The fetch() method takes only one parameter which is the URL of the resource i. e API endpoint that you want to fetch.
const response = (url) => {
fetch(url)
.then((res) => res.json())
.then(
(result) => {
console.log(result);
},
(error) => {
console.log(error)
}
);
};
and the Fetch API is very simpler and cleaner to use, Fetch API uses the Promise to produce more flexible features to make requests to servers from the client.
React Js fetch data from API functional component
EmployeelistFun.js
import React, { useState, useEffect } from "react"
const EmployeelistFun = () => {
const [employeeslist, setemployees] = useState(null)
useEffect(() => {
getemployees()
}, [])
const getemployees = () => {
fetch(" http://restapi.adequateshop.com/api/Metadata/GetEmployees")
.then(res => res.json())
.then(
(result) => {
setemployees(result)
},
(error) => {
setemployees(null);
}
)
}
if (!employeeslist) return (<div>No Record Found</div>)
return (<div>
<h2>Employees List Funcational Component </h2>
<table className="table" >
<thead>
<tr>
<th>Employee Id</th>
<th>Name</th>
<th>Address</th>
<th>City</th>
<th>ZipCode</th>
</tr>
</thead>
<tbody>
{employeeslist.map(emp => (
<tr key={emp.Id}>
<td>{emp.Id}</td>
<td>{emp.Name}</td>
<td>{emp.Address}</td>
<td>{emp.City}</td>
<td>{emp.ZipCode}</td>
</tr>
))}
</tbody>
</table>
</div>)
}
export default EmployeelistFun;
React fetch data from API Class component
Employeelist.js
import React from 'react';
class Employeelist extends React.Component {
constructor(props) {
super(props);
this.state = {
employees: [],
IsApiError: false
}
}
componentDidMount() {
fetch(" http://restapi.adequateshop.com/api/Metadata/GetEmployees")
.then(res => res.json())
.then(
(result) => {
this.setState({
employees: result
});
},
(error) => {
this.setState({ IsApiError: true });
}
)
}
render() {
var employeeslist = this.state.employees;
debugger;
if (employeeslist && employeeslist.length > 0) {
return (<div>
<h2>Employees List Class Component</h2>
<table className="table" >
<thead>
<tr>
<th>Employee Id</th>
<th>Name</th>
<th>Address</th>
<th>City</th>
<th>ZipCode</th>
</tr>
</thead>
<tbody>
{employeeslist.map(emp => (
<tr key={emp.Id}>
<td>{emp.Id}</td>
<td>{emp.Name}</td>
<td>{emp.Address}</td>
<td>{emp.City}</td>
<td>{emp.ZipCode}</td>
</tr>
))}
</tbody>
</table>
</div>)
}
else {
return (<div>No Record Found</div>)
}
}
}
export default Employeelist;
Step 4 – Import Component in App.js.
App.js
import logo from './logo.svg';
import './App.css';
import Employeelist from "./components/Employeelist";
import EmployeelistFun from "./components/EmployeelistFun";
function App() {
return (
<div className="container">
<Employeelist/>
<EmployeelistFun/>
</div>
);
}
export default App;
I’m assuming that you are familiar with React Js framework and creating React Js applications. If not then please go through the following articles:
The post React Js- Fetch data from API using hooks appeared first on Software Development | Programming Tutorials.
Read More Articles
- React.js: loading JSON data with Fetch API and props from object array
- How to make the API call and display it in React JS using React Table and Axios?
- React Context : Get Data from API and call API whenever some events happens in React Component
- How to fetch data from api and pass it as props
- displaying data from fetch api using react
- Get object data and target element from onClick event in react js
- Where do I fetch initial data from server in a React Redux app?
- How to fetch API data from Axios inside the getServerSideProps function in NextJS?
- Set the data in React Context from asynchronous API call
- React Custom Hooks fetch data globally and share across components?
- Paginate date-specific results from an API with React and Redux
- Using useEffect() Hook and Async/Await to Fetch Data from Firebase/Firestore
- React Select - How to show / iterate through data from api call in option instead of hardcoding options?
- How to upload an Excel sheet file using react.js and display data to a table
- How to fetch data and store in React Context API?
- React useEffect hook and Async/await own fetch data func?
- React - Fetch from external API function on button click
- React and Flux: "dispatch in the middle of a dispatch" to show error message from an API call
- Post an object with fetch using react js and express API server
- Importing data from excel and displaying in a react component
- How do I access data returned from an axios get to display on a web page using react js?
- How to edit react bootstrap table and save data after editing
- How can I cache data that I already requested and access it from the store using React and Redux Toolkit
- how to display data in table using json in react js?
- React - this.state is null inside render when getting data from API
- React Hook useEffect : fetch data using axios with async await .api calling continuous the same api
- REACT - Set initial data in Formik Form after fetching from API
- How can I cache data from API to Cache Storage in React PWA?
- How to activate a react route and pass data from the service worker?
- Can't access to my data from a SWR fetch - React
- React onMount animations
- Error trying to install react native, not building correctly when running pod install
- How to inject dotenv variables without REACT_APP prefix in create-react-app?
- Property 'auth' does not exist on type 'FirebaseApp' on REACT
- Injecting gatsby-image into html created from markdown using ReactDOMServer.renderToString
- How to update state in specific rows in a table ReactJS
- Scrollable List Component from Material-UI in React
- Error: Form submission canceled because the form is not connected
- Detect bottom of page to fetch more data in react
- Testing a React Modal component
- How to use useStyle to style Class Component in Material Ui
- React router private routes / redirect not working
- Why is create-react-app's build directory in .gitignore?
- How to make webpack not use the window object when bundling?
- Using Dygraph in React with redux?
- Cancel All Subscriptions and Asyncs in the componentWillUnmount Method, how?
- How to serve robots.txt and sitemap.xml in firebase hosted create-react-app with react-router
- Ternary operator on style with React Js Es 6
- Download a string as .txt file in React
- Semantic react ui Popup close button