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
- How to fetch and display data from Express API to a React app?
- How to properly fetch data from several API calls and display it to the DOM in React
- How to fetch and display data from json file in react typscript
- How to fetch data from a custom React hook (API) with onClick and display it in a Div using TypeScript?
- How do I display data from api using react and redux
- ReactJS Fetch User Data from API and add to table
- How to load and display data with React from an API running on localhost
- Display data from API using react component and useEffect
- Fetch data from api and rearrange it in react
- How to fetch data from API and then pass it to another component in react after it is fully loaded?
- React App: How to display data from api using fetch
- Best way to fetch data from a REST api using react hooks and context for state management?
- How to display a spinner when data is loading from server by fetch api in REACT JS?
- How to fetch and display data from documents in subcollection in react
- Display data in a single table in React Sharepoint from two REST API or from 2 different getbytitle name
- Fetch image based on text and display from API react
- Matching Data from two api calls and then displaying results on the table in React
- React Display Data from API Fetch & Map
- Fetch data from API when form's search button clicked and show data on another page in React JS
- Fetch and display data on React bootstrap Table
- ReactJS can't fetch and display data from localhost API
- How to display POST API data containing string using fetch and map function in React
- React - Fetch Data from API and map nested JSON
- How can I fetch data from mongoDB and display it on react front end
- trying to fetch data from api and show it in react native flatlist and my code displays data in console log,but it didnt render in emulator
- 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
- Babel + Jest Configuration
- Reactstrap Navbar align items right
- In react.js, is it better to call an external API upon form submission or within componentDidMount() of subsequent component?
- Can't write firestore tests because of: FIRESTORE (9.6.1) INTERNAL ASSERTION FAILED: Unexpected state
- Change attribute of JS widget direction=rtl into dir=rtl
- React Map Operator
- react-aad-msal authProvider.getAccessToken() reloads the component indefinitely
- avoid opening new window when downloading s3 object
- React router in TypeScript- both router and own props
- React Redux fetch data before render and do a map function
- How to refactor code using styled components in react and typescript?
- Change the position of Tabs' indicator in Material UI
- Django Rest Framework Forbidden when i send post request
- ReactJS + Redux, getting error "Failed prop type: Right-hand side of 'instanceof' is not callable"
- how to leave table rows opened on react table?
- How to dynamically add data to a table via map/if or terinary operator in JSX
- Search nested array of objects and return whole path of all matching items
- How to avoid display error when filtering > 0 in the middle of the map
- Creating a table in react using multiple component calls not working
- React button lifecycle
- What is the methodology or pattern used to create a ReactJS front end that is more or less a series of components you can turn on/off
- How to destructure from a separate destructured property in a single line?
- Using Map in React with firebase
- React Js / using setTimout on jsx with state
- Displays [object Object] instead of label name
- Parameter 'initialState' cannot be referenced in its initializer
- How to call dispatch without using store
- React isn't updating a variable from a function
- Wrapping elements of varying length X times before overflowing
- Background Images not showing after deployment
- Why do my two click events in my React app run at the same time?
- Merge Sort not working as expected in React
- How to access method of the child component from parent in reactjs
- ReactJS keeping a single "Active" state between multiple components
- In React, Is it good practice to search for certain element in DOM?
- React form hooks How to validate select option
- My React site only show home page, all other pages not found after upload on live server
- React Hooks - Dynamically Render Text Inputs and Store Inputs as One Array
- Property 'palette' is not recognised by DefaultTheme from MaterialUI, it stopped to work once material ui have been moved from v4 to v5
- React/TypeScript error: Operator '<' cannot be applied to types 'boolean' and 'RegExp'
- Set pagination on MaterialTable ui https://material-table.com/#/docs/features/localization?
- How to convert SVG into React Component?
- Trying to load content with useEffect and context
- Updating CSS Module @Value with React
- How to deploy a create-react-app to a web host (ex. Siteground)?
- Dynamically render routes in react-router 5.1
- React: How to add onChange functionality inside of Function component using React Hooks? Need onClick event from a checkbox to influence input state
- How to get Material-UI Drawer to 'squeeze' other content when open
- how to get array kets on selecting value from react search auto select
- caching issue with web application developed using reactjs & webpack
- Recharts not working in React - 'recharts' does not contain an export named 'Recharts'
- Cannot find module 'ReactNative' from 'react-native.js' w/ Jest
- Meteor/React, redirect route after changeState
- How can I update only a single cell value and JSON in table
- How to avoid memory leaks with React Hooks
- Not getting desired values in input fields React redux or ReactJS
- reload component - React
- How do you render objects from json
- Remove Readonly when it is clicked outside of the input in React
- How do I set the default value of a <select> element in React?
- My repository is using CI/CD, but I have this error. How can I fix it?
- Mocking child component properties jest+enzyme+react
- Reactjs: Unknown why function re-run second time
- Conditionally setting className based on a state variable in a React functional component
- ReactJs adding Third party Javascript Plugin
- Error handling in react router server-side
- Target fragment within react const
- Convert SVG SMIL linear gradient animation to CSS animation
- Need to find object from an array with two objects
- ReactJS: e.preventDefault() is not a function
- Table iteration in React conditional rendering
- How to use <select><option value={true}> in React?
- formik nested dynamic object
- Binding functions in react js
- how to change color of Backbutton Arrow in react native router flux?
- .velocity is not a function
- jsonwebtoken in react have an error "Cannot read property '2' of null"
- Identifying component from multiple components
- Show React component as popup using Typescript
- Clicking like icons increases the like count of other components
- Why am I receiving jwt malformed?
- How to Use componentDidMount() in Functional Component to execute a function
- React throws CORs errors when moving recaptch ready callback
- Wait for change of prop from parent component after changing it from a child in React
- What's difference between two ways of defining method on React Class in ES6
- react props undefined inside the constructor and exist inside the render
- How do I rewrite this with 'recompose'?
- How to update state of the component with data from API
- useEffect Error: Minified React error #321 (GTM implementation instead of google analitycs)
- Can you hide a html button based on user source ip
- React-Table returning remaining items after filtering?
- react hook form: how can i validate a group of radio buttons or checkboxes to ensure at least one is selected
- How do I delay animate, not whileOver or WhileTap in framer motion?
- Partytown implementation with React.js
- React this.state is undefined in component function
- Type error with HOC in React and TypeScript
- How to push inside nested array of object that have a precise value of a key in MongoDB?
- Results are not populating after fetching from API using React
- React Testing Library / Redux - How to mock cookies?
- React Universal pass data to component
- how to display none of the grid.col part when page is loading using react
- React DVA JS Framework: Reset entire state application
- React can't read JSON local file value inside component
- getting issue in text not in proper line
- When using @react-three/drei useGLTF crashes scene
- Retaining Firebase auth credentials after redirect
- get clicked button's name
- React: state-based styling
- Webpack Code Splitting: Does it do anything? Seems like no effect
- TypeError: Cannot read properties of undefined (reading 'name') reactjs
- Merge classes with JSS instead of overriding
- Col width in React Bootstrap
- react-chartjs-2: How to customize the onHover tooltip
- redux thunk calling two different api requests
- Error "SyntaxError: Cannot use import statement outside a module" when deploying React app with Netlify Functions
- Selected option in localstorage
- How can I get ownProps using reselect on redux?
- Material-Ui theme customization: hover on contained button
- Property in state becomes undefined within action creators
- use ! in Reactjs Component in JSX
- How to update react state without re-rendering component?
- front slash changes to back slash after #
- React conditional rendering bug even with single parent and child list
- Ionic/Capacitor React App API Requests returning HTML on iOS
- Testing react-router v4 with Jest and Enzyme
- Inline background-image in React
- How to add a custom label title to <svg> content generated with Javascript?
- Keep text formatting in MongoDB
- how to use react require syntax?
- Input values are syncing up and I'd rather they not
- React Hook useRef return style property as null
- Material Ui Accordion closes automatically
- Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'express' imported from F:\Document\My Project\NODE JS\Sample 1\tinder-backend\server.js
- Aligning text in th tag in JSX
- Inputs not changing when removing list items from state
- How to return a re-tried response from axios interceptors
- React and progress bar. How can I add progress bar that will work with my input and my data
- React Wrapping up component around js content
- TypeScript Type for HTML Element Tag
- TypeError: Cannot read property 'profile' of undefined
- react-router dynamic routing instead of pattern matching
- alternative to innerRef when using hooks
- How to update state on disabled field in react
- How to change the style of an element retrieved from JS getelementbyid in react?
- ReactJS nested data structuring
- Unable to install FluentUI packages for react app
- `App` - not retrieves the store static value
- can't open new tab in react, adds localhost:3000 on link?
- Resolve Relative Path from node_modules to Dist folder with Webpack
- React GraphQL Relay - How to do a simple query?
- how to set react useState in useEffect and in window.addEventListener
- Log setState calls
- React keeps aborting installation when I try the tutorial
- Error: Uncaught ReferenceError: React is not defined
- I want to change className of a div after push
- (P)react trigger method in functional ChildComponent
- is there any way to use lowercase letter for a component in ReactJS?
- Create arrays with number in ascending order
- How do I hide the swiper pagination for specific slides in react?
- onClick dont call the function
- What's the alternative to use hooks inside non React component?
- rootInstance.findByType("input"); Giving Expected 1 but found 2 instances with node type : "undefined"
- I cannot use history.push() properly with ReactJS
- How to display the date month and year in a specific format using javascript and react?
- react router v4 programmatically change route
- Why doesn't useEffect render my graph on startup?
- React memory leak warning
- How to allow scss in jest for unit testing for typescript nextjs?
- What's the idiomatic way to pass component prop to a component in Vue.js?
- How to set custom style to antd Rate Component