In this post, we are going to discuss Fetch data from API and display it in table React Js in a functional component
we can easily fetch the data inside a functional component using Hooks.Hooks are functions that allow us “hook into” React state and lifecycle features from function components in our application. let you know that we can not use Hooks inside classes.
One more important feature of Hooks is that Hooks allow us to split one component into smaller functions based on what pieces are related, rather than forcing a split based on lifecycle processes.
React JS provides a built-in Hooks like useState and we can also create our own Hooks to reuse stateful behavior in components.
Make API calls out of React Functional Component
API ENDPOINT:https://reqres.in/api/users?page=1
{
"page": 1,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 1,
"email": "george.bluth@reqres.in",
"first_name": "George",
"last_name": "Bluth",
"avatar": "https://reqres.in/img/faces/1-image.jpg"
},
{
"id": 2,
"email": "janet.weaver@reqres.in",
"first_name": "Janet",
"last_name": "Weaver",
"avatar": "https://reqres.in/img/faces/2-image.jpg"
},
{
"id": 3,
"email": "emma.wong@reqres.in",
"first_name": "Emma",
"last_name": "Wong",
"avatar": "https://reqres.in/img/faces/3-image.jpg"
},
{
"id": 4,
"email": "eve.holt@reqres.in",
"first_name": "Eve",
"last_name": "Holt",
"avatar": "https://reqres.in/img/faces/4-image.jpg"
},
{
"id": 5,
"email": "charles.morris@reqres.in",
"first_name": "Charles",
"last_name": "Morris",
"avatar": "https://reqres.in/img/faces/5-image.jpg"
},
{
"id": 6,
"email": "tracey.ramos@reqres.in",
"first_name": "Tracey",
"last_name": "Ramos",
"avatar": "https://reqres.in/img/faces/6-image.jpg"
}
]
}
Component Code
Userlist.JS
import React, { useState, useEffect } from "react";
const Userlist = () => {
const [userList, setusers] = useState(null);
useEffect(() => {
getuesers();
}, []);
const getuesers = () => {
fetch("https://reqres.in/api/users?page=1")
.then((res) => res.json())
.then(
(result) => {
console.log(result.data);
setusers(result.data);
},
(error) => {
console.log(error);
setusers(null);
}
);
};
if (!userList) return <div>No Record Found</div>;
return (
<div>
<h2>Fetch data inside Funcational Component </h2>
<table className="table">
<thead>
<tr>
<th>User Id</th>
<th>Name</th>
<th>Address</th>
<th>City</th>
<th>ZipCode</th>
</tr>
</thead>
<tbody>
{userList.map((user) => (
<tr>
<td>{user.id}</td>
<td>
<img
src={user.avatar}
style={{ height: "50px", borderRadius: "50%" }}
></img>{" "}
</td>
<td>{user.email}</td>
<td>{user.first_name}</td>
<td>{user.last_name}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
export default Userlist;
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:
In the above example, useState is the Hook that needs to call inside a function component to add some state to it. The useState returns a pair, the first element is the current state i.e initial value, and the second one is a function that permits us to update it. you can understand useState is similar to this.setState in a class component.
The post React Js- Fetch data from API on button click appeared first on Software Development | Programming Tutorials.
Read More Articles
- How to fetch data from API and then pass it to another component in react after it is fully loaded?
- How to fetch data from API for multiple items in React JS component
- React component is unable to fetch data from api
- React Context : Get Data from API and call API whenever some events happens in React Component
- Passing API data from parent container to child component in React
- displaying data from fetch api using react
- How to make React.js fetch data from api as state and pass this state data from its parent to child component
- How to pass data from vanilla JavaScript to React functional component
- How to Read image data from API and render in React Component
- How to fetch and display data from Express API to a React app?
- React fetch all data from api at startup
- Getting undefined when trying to fetch data from an api - React
- How to iterate through a list of objects from api and render it to jsx page React functional component
- React fetch api data to component
- How to handle asynchronous fetch from Database with Gatsby or React functional component
- React Hook to fetch data from APi when click 2 different button
- How to access data from get request made by a React functional component to localhost server using Axios?
- How to call a react hook fetch request in a functional component to access data then pass to a class component to map?
- React JS fetch data from multiple API function
- How to get React to re fetch my data from API after a POST or DELETE to Database?
- How to display data from api in react component
- Fetch random data from API without refreshing the page in react axios
- Display data from API using react component and useEffect
- How to update React State in Functional Component while fetching data using API
- Fetch data from api and rearrange it in react
- How to fetch sequence api calls where second api call need particular data from first api call result using react hooks?
- React Redux, load data from the API on first page load ONLY. Render component once data is loaded
- React hooks - fetching data from api and passing to a component
- How can I filter json data from api call in react into different sections of the component
- React App: How to display data from api using fetch
- How to use two map function with two fetching url
- You must pass a component to the function returned by connect. Instead received undefined
- How to render component again at the top level with the new props in React 0.14
- Background image in react-admin Login page
- React - Functional Component for PrivateRoute, and for in index file
- SetState with react hook and redux after async call to axios API
- Removing icon when there are no children
- How to make image responsive in Material-UI
- React filter items with dropdown
- Trouble using jquery-csv library
- network error in axios on node.js request
- Add a new value inside the State object in React Hook
- handling arrays in javascript
- How to "override" the render function?
- Getting CORS / Origin Error When Calling External API
- State not persisting between functions with useState
- Module not found: Can't resolve 'firebase' in
- Traversing Through List of Objects in React/Jsx
- Generate unique notification from a value in object
- How to format a string in UTC to the configured timezone on Moment
- How to get Date and Time in Firebase Timestamp in react js
- How to display loading info based on clicked delete button in reactjs
- Return books that contain specific genres
- React.js Pane seems to crash when an Array of Objects is added to hook
- setState does not update array state in React Js
- "npm start" error with webpack-dev-server
- How to add ReactDom to global namespace in Meteor
- React: onClick on button not working
- react-chartjs-2 does not show line until window is resized
- How to get React onClick to work? (Doesn't work even with arrow function)
- Can I disable an anchor tag with respect to an if condition which return a string
- How to handle 2 Header in reactJS?
- Accessibility - React Ensure click events have key events
- html / css: align texts when there is another element before texts
- how to use useMutation or useQuery as hook on React or React Native?
- Navigate to different page on successful login
- How to push multiple json (response ) in single array?
- RTK Query with AppSync returns status "rejected"
- TypeError: Cannot set property '_eventListeners' of undefined
- How can mutating `this.state` and then immediately calling `setState` break?
- React Router v4 not rendering anything when files separated
- Changing currentTime using React Component State
- How to customize a div's scroll bar with css modules?
- How to implement a redux middleware class in TypeScript
- Replace parent state with state of child. Button in parent
- Using boolean values for <option> values in React
- this.props 'missing' method using conect from react-redux
- RegEx Data Values Javascript white Space
- ReactJs is not reading map function inside useEffect
- Re-export bundled React for other Webpack bundles
- Unknown Prop Warning when React.cloneElement used
- How can I render multiple components while looping through an object and then interpolate the JSX associated?
- Is there a way to get a download percentage from a fetch request in React?
- Dispatch isn't working in my contextAPI (functional component)
- How to mock all files in a folder in jest
- Type '{ 'x-access-token': any; } | { 'x-access-token'?: undefined; }' is not assignable to type 'AxiosRequestHeaders | undefined'
- How to display the data related when an option is clicked on drop down?
- Component crashes when re-render
- How do I pass selected values from drop down during on click on Next button
- using onChange with es6
- Initialize / Eager Load React Component in Background on App Start for later usage
- One function does not work inside another in React Native
- Hide some React component children depending on user role
- handleSubmit and onChange handleSubmit resulting in setState error or cannot enter character
- Yup optional field validate number - React Hook Form
- How to call a function and then navigate to a route when click on a button?
- react-moment where to set moment.locale
- Docusaurus 2 How to add custom react component in navbar
- How to avoid duplicates using material-ui autocomplete?
- React does not render correct on page refresh
- How to repeat escape character n times in JSX
- How do I properly use formik reset form?
- Render a react component on a wordpress page
- How to retrieve Azure Key Vault in React JS
- Is it possible to add user search filters to a ReferenceManyField in React Admin v3?
- Webpack not loading output files in localhost even after compiling successfully
- ReactJs useState sets blank text for first time
- Attempted import error: does not contain a default export
- React select Icon click
- Django React Axios
- Canvas .tsx - Object is possibly 'null' and Property 'getContext' does not exist on type 'never'
- React Cannot update a component from inside the function body of a different component
- How to display submenu links in React
- How can i make a different oath flow between login & signup for social? like google oauth2.0 using passport js
- Relative Interface (TYPESCRIPT)
- Update UI when useRef Div Width Changes
- How can I customize the action icons in Material Table dynamically?
- React: Validate that no extra props has been passed
- State change not re-rendering component
- What are the keys in redux-persist v5 config's blacklist and whitelist?
- Wordpress Gutenberg autocomplete - saving attributes
- Reactjs how to add variable in URL parameter
- React Load hashed image from data while loading Image
- Handle new Redux for a global search filter
- Delete request in React
- how to display a div with multiple conditions in reactjs
- Using material-ui autocomplete with dividers
- Why isn't JSX saved as a const rendering
- Babel with .babelrc how to fix MODULE_NOT_FOUND?
- Cannot read properties of undefined (reading 'map') react JS
- Exporting Jest test results to txt
- Sticky HTML table header works, but header outline disappears when scrolling
- Material ui select move the scroll to top if all items are selected
- react router render app and login
- Maping and changing states in Redux
- Mock function not being called with react-testing-library, but original function is called
- How to arrange array inside array data in reactjs?
- Sorted assets on name or id
- How to style Link from the react-dom-router module?
- How to implement a horizontal scrollview like an appstore
- Using react-with-styles in recompose
- How do i have my content appear right beside my sticky sidebar?
- How to export hooks to other functions in react.js?
- Why axios not submitting data to asp.core api
- How can I set a a state variable to an object in react?
- React error: Can only update a mounted or mounting component
- Issue accessing state array from inside animationFrame with react
- How to Pass a Variable from Child to Parent
- Execute different component's function
- How to position a div relatively to an image?
- Unit test on redux that involves a firebase call
- childrens ID's are getting duplicate under chakra UI MENU component
- well-known routes Kubernetes
- Why I am getting this error: Error: failed to process internal error: entered unreachable code: assign property in object literal is invalid
- how to remove / unmount nested react components
- Type assignment error in typed reducer callback
- Reactjs which one is better form onChange or input onChange?
- React Navigation add save button
- Webpack react-hot-loader not working
- Cache like component in reactjs
- history.push not redirecting me to the Home
- How to optimize multiple variable check
- How to import an useState object from another folder
- React Context is not updating
- Error trying to render a table dynamically
- Sending input value to click handler in React
- display checked in react
- create-react-app MaterialUI Error: Invalid hook call
- Receiving attempted import error for typography file
- How can I add compoent to another component in React?
- docker-compose up exit with code 0 for react js
- jest updateSnapshot for specific test file
- Cannot read property 'username' of undefined error
- How to get rid of Typescript type error when overriding MuiContainer classes?
- Button in label for custom file selector field
- React onClick function variable undefined, but should work during runtime, how should I fix this?
- Unable to update an Individual Searchbox with popup modal in React/Typescript
- React-Native Invariant Violation: Element type is invalid
- split from_date and to_date to a list of date range array
- how to format a date inside a reactjs component
- Catch 504 (Gateway Timeout) Error in React, JavaScript
- Change component value
- call a function from another class in react
- How to properly get a react fresh state before rendering the component?
- Can anyone explain why this returns between 50 to 100 of the same values? I am using this to change what a function does at a certain window width
- How to return a filtered map in jsx?
- React emotion-theming not working during server-side rendering
- failed to get img displayed using forEach in react
- Handling signin flow in React
- Can't import Google Fonts with Styled Components and Next.js
- How to use Django's session authentication with Django Channels?
- display an image from an array of images to a modal using react hooks
- How to display background color in CSS not working?
- React Router: How to navigate to another component using anchor tags
- How to show react and angular on same page using micro-frontend Runtime integration approach?
- Howler JS & React AudioContext console warning
- Where should I keep data models in React and Redux?
- How can i change name of a btn after login in react?
- Mock componentDidMount lifecycle method for testing
- Async await or .then() are returning undefined for redux actions