If you are a beginner for Reactjs and trying to improve yourself with a test project and you are looking for calling and fetching the data from the rest API using Axios then you have come to the right place.
In this project, we will set up a structure such that the UI component will connect to REST API, and use the returned data this has many examples on the internet but in this article, we are going to discuss the same concept using Axios.
For showing you an example I’m using the below example API for getting the data.
1.GET http://restapi.adequateshop.com/api/TravelAgent
Json Response
[
{
"id": 122409,
"agent_name": "Mike",
"agent_email": "mike921@.com",
"agent_location": "Paris",
"createdat": "2022-05-20T07:15:59.7729513"
},
{
"id": 122408,
"agent_name": "Mike",
"agent_email": "mike921@gmail.com",
"agent_location": "Paris",
"createdat": "2022-05-20T07:13:06.7843333"
},
{
"id": 122407,
"agent_name": "KartikBandi",
"agent_email": "bandikarthik@gmail.com",
"agent_location": "Armoor",
"createdat": "2022-05-20T07:08:22.5717523"
},
{
"id": 122391,
"agent_name": "guruswamy",
"agent_email": "guruswamy12@gmail.com",
"agent_location": "india",
"createdat": "2022-05-20T05:32:35.1775134"
},
{
"id": 122389,
"agent_name": "sdsd",
"agent_email": "sdsd@gmail.com",
"agent_location": "sdsd",
"createdat": "2022-05-20T05:27:51.8326946"
},
{
"id": 122388,
"agent_name": "dhiraj shende",
"agent_email": "ds1j@sdshghdk.com",
"agent_location": "IND",
"createdat": "2022-05-20T05:27:40.5961154"
},
{
"id": 122387,
"agent_name": "yashwitha",
"agent_email": "OZSZDW@gmail.com",
"agent_location": "US",
"createdat": "2022-05-20T05:11:38.4162423"
},
{
"id": 122079,
"agent_name": "rupal",
"agent_email": "rupall22@gmail.com",
"agent_location": "india23232",
"createdat": "2022-05-19T13:10:26.8226353"
},
{
"id": 122078,
"agent_name": "abhishek",
"agent_email": "abhishek80@gmail.com",
"agent_location": "india",
"createdat": "2022-05-19T13:07:22.3235079"
},
{
"id": 122077,
"agent_name": "mahendra",
"agent_email": "mahendra98@gmail.com",
"agent_location": "rRatlam",
"createdat": "2022-05-19T13:05:09.2087452"
},
{
"id": 122076,
"agent_name": "Dnady",
"agent_email": "dandywdasd@gmail.com",
"agent_location": "iNdoneisa",
"createdat": "2022-05-19T13:03:27.5413588"
},
{
"id": 122074,
"agent_name": "dhiraj shende",
"agent_email": "ds1j@sdsdkjkdjddhjs.com",
"agent_location": "IND",
"createdat": "2022-05-19T13:01:08.7516211"
},
{
"id": 122072,
"agent_name": "Elif Sinano?lu",
"agent_email": "elif.sinanoglu@example.com",
"agent_location": "Bart?n",
"createdat": "2022-05-19T12:57:33.6831017"
},
{
"id": 122069,
"agent_name": "Ilija Milanoski",
"agent_email": "${RndEmail}.com",
"agent_location": "Vigo",
"createdat": "2022-05-19T12:56:56.2610036"
},
{
"id": 122068,
"agent_name": "Jesus Benitez",
"agent_email": "jesus.benitez@example.com",
"agent_location": "Vigo",
"createdat": "2022-05-19T12:56:55.8662293"
},
{
"id": 122064,
"agent_name": "Cecilie Wojcik",
"agent_email": "cecilie.wojcik@example.com",
"agent_location": "Bud",
"createdat": "2022-05-19T12:56:14.4489244"
},
{
"id": 122061,
"agent_name": "Xavier Ross",
"agent_email": "xavier.ross@example.com",
"agent_location": "Keswick",
"createdat": "2022-05-19T12:55:41.3629308"
},
{
"id": 122056,
"agent_name": "Ilija Milanoski",
"agent_email": "kenan.cetin@example.com",
"agent_location": "Van",
"createdat": "2022-05-19T12:55:12.2889649"
},
{
"id": 122019,
"agent_name": "nimisha",
"agent_email": "n",
"agent_location": "USA",
"createdat": "2022-05-19T12:36:12.6214081"
},
{
"id": 122015,
"agent_name": "dhiraj shende",
"agent_email": "ds1HJjhjjjr323kjskjkjkjl2jkjkjkk3@kjkjjhjhds.com",
"agent_location": "IND",
"createdat": "2022-05-19T12:22:19.3782778"
}
]
If you are looking for a sample rest for testing purposes then visit here, in this article I have listed a sample test API for testing purposes.
For that, I created a FetchDataFn.js file, that is the UI component, and for API calls, using Axios.we are going to Fetch and display data in a table using bootstrap from API in React JS using Axios.
Step 1. Install Axios library in our project
npm install axios –save axios
Step 2.Install bootstrap in our project for using bootstrap table.
npm install react-bootstrap bootstrap
Step 3:Write code
Axios React functional component
FetchDataFn.js
import React, { useState, useEffect } from "react"
import axios from 'axios';
import { Table, Button } from 'react-bootstrap';
const FetchDataFn = () => {
const [agents, setagent] = useState(null)
useEffect(() => {
getagents()
}, [])
const getagents = () => {
axios.get('http://restapi.adequateshop.com/api/TravelAgent').then(response => response.data).then(
(result) => {
setagent(result)
},
(error) => {
setagent(null);
}
)
}
if (!agents) return (<div>No Record Found</div>)
return (
<div>
<h2>Fetch data in Funcational Component </h2>
<Table className='table'>
<thead className="btn-primary">
<tr>
<th>First Name</th>
<th>EmailId</th>
<th>Address</th>
<th>CreatedAt</th>
</tr>
</thead>
<tbody>
{agents.map(agent => (
<tr key={agent.id}>
<td>{agent.agent_name}</td>
<td>{agent.agent_email}</td>
<td>{agent.agent_location}</td>
<td>{agent.createdat}</td>
</tr>
))}
</tbody>
</Table>
</div>
)
}
export default FetchDataFn;
Axios React class component
if you are looking for example Fetch and display data from API in React JS using Axios in class component then look at below example.
import { Table, Button } from 'react-bootstrap';
import axios from 'axios';
import React from 'react';
const apiUrl = 'http://restapi.adequateshop.com';
class FetchData extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
agents: [],
response: {}
}
}
componentDidMount() {
axios.get(apiUrl + '/api/TravelAgent').then(response => response.data).then(
(result) => {
this.setState({
agents: result
});
},
(error) => {
this.setState({ error });
}
)
}
render() {
const { error, agents } = this.state;
if (error) {
return (
<div>Error:{error.message}</div>
)
}
else {
return (
<div>
<Table className='table'>
<thead className="btn-primary">
<tr>
<th>First Name</th>
<th>EmailId</th>
<th>Address</th>
<th>CreatedAt</th>
</tr>
</thead>
<tbody>
{agents.map(agent => (
<tr key={agent.id}>
<td>{agent.agent_name}</td>
<td>{agent.agent_email}</td>
<td>{agent.agent_location}</td>
<td>{agent.createdat}</td>
</tr>
))}
</tbody>
</Table>
</div>
)
}
}
}
export default FetchData;
While managing web applications in React, the most widely recognized task is to speak with backend servers. This is normally done through HTTP convention.
We are intimately acquainted with the exceptionally normal XML Http Request connection point and Fetch API, which permits us to bring information and make HTTP demands.
There is one more method for speaking with the backend in React, and in this article we will find out about the wonderful library known as Axios and a portion of the critical elements of Axios that have added to its prominence among frontend designers.
So we should get everything rolling.
What is Axios? (A tad of history)
Axios is utilized to speak with the backend and it additionally upholds the Promise API that is local to JS ES6.
It is a library which is utilized to make solicitations to an API, return information from the API, and afterward get things done with that information in our React application.
Axios is an extremely famous HTTP client, which permits us to make HTTP demands from the program.
For what reason Do We Need Axios in React?
Axios permits us to speak with APIs effectively in our React applications. However this can likewise be accomplished by different techniques like get or AJAX, Axios can give a tiny amount of greater usefulness that makes a remarkable difference with applications that utilization React.
Axios is a guarantee based library utilized with Node.js and your program to make nonconcurrent JavaScript HTTP demands.
Whenever we realize we want to execute some guarantee based nonconcurrent HTTP demands in our application, with JavaScript, we normally consider just jQuery’s AJAX or get strategy to take care of business. And keeping in mind that doing as such, we are really conflicting with React!! Did you see that?
The post React Js- Fetch data from API on button click 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 fetch data from a custom React hook (API) with onClick and display it in a Div using TypeScript?
- Using data from API JSON object using Axios and React
- How do I display data from api using react and redux
- Display data from API using react component and useEffect
- React App: How to display data from api using fetch
- React and Express: Using Axios to GET data from 3rd party API
- Best way to fetch data from a REST api using react hooks and context for state management?
- Display API data using Axios and a list in React
- Fetch QrCode SVG from API using axios and show it in a div in react
- How to display POST API data containing string using fetch and map function in React
- How to concatenate URL and string, and get data from API at click a button using axios in REACT JS
- How to properly fetch data from several API calls and display it to the DOM in React
- How do I access data returned from an axios get to display on a web page using react js?
- React Hook useEffect : fetch data using axios with async await .api calling continuous the same api
- displaying data from fetch api using react
- Fetch data using an id from an api but display an alternative text to address bar e.g. content_title in Next.js
- Download file from Express API using React and Axios
- How to fetch and display data from json file in react typscript
- How to load and display data with React from an API running on localhost
- Fetch random data from API without refreshing the page in react axios
- fetching data from the Dog API using axios and saving data into a new array
- 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?
- How to fetch sequence api calls where second api call need particular data from first api call result using react hooks?
- how fetch data from database through api using axios in reactjs?
- How to use axios to fetch data from servlet and then crossfilter it and display via highcharts
- Fetching Data from API using NextJS and Material UI React
- How to fetch data from api in React by using axois?
- React useEffect looping many times when fetching data and setState using fetch API
- React Router 4 authentification and redirection
- How to get props before event Render
- useEffect always sets my addEventListener
- how do I fix this ant design datepicker component in my react project .I have shared a screenshot
- JSX template literals for an inline style
- React JS: Array is not being passed to state
- how to use a object key with " - " in the middle
- Unicode JSON in Laravel blade for use in React, generating a JSON.parse problem
- How to compile the JS file to use a React component in a WordPress theme if I do not need SSR?
- Validating React-Bootstrap-Typeahead input
- Can't use React.findDOMNode function
- How to use Redux-Saga with Hooks to call API
- Zustand is updating all the components on single property state change
- React: Logging state of a parent from a child component yields different results
- How does webpack v4 handle devDependencies in production mode?
- React context api only render components that use values that have changed
- Alter Object Array in React with useState-hook without deep copying
- error message without submitting the form
- For Loop doesn't render components probably
- Pass state to a component in another file in react
- React component background image not fitting properly into the container when resizing the window
- List element value returns wrong values when accessing attribute
- how to show different content when mapping over an array when less items
- ReactJS KonvasJS How to create 2 layers that cannot overlaps
- transform "Route children" and "cloneElement" to RouterV4
- How can I set icon size in react
- How to change a hook inside text input in React.js?
- React children with typescript
- React + D3 + Force-Directed Tree + Adjustable Link Strength
- ReactJS project on Android WebView, Image not showing
- Bind specific redux action to one Route using react-router / react-router-redux
- React-router + typescript type error
- React and localstorage
- Update nested array in this.setState
- How can you add styles in reactJs for show/hiding google maps?
- Serve static html files in PWA if service worker is configured in CRA
- ReactJS + Redux + Reduc-thunk Can't dispatch promise
- Dynamic import not working in netlify (reactjs)
- How to change the color of the primary Material UI
- Froala in ReactJS application: Inline editing
- Filter data inside map and return content only if is set to "true"
- React, Axios, PokeAPI return undefined when setting hook using "nested" fetches
- Function is not working in React outside render()
- How do I push useRouter to a new url with Nextjs?
- How to get text content of elements in a div onClick? React.js, JavaScript
- Running a for loop inside a function called in react's render method
- Refactor componentWillReceiveProps to Hook
- How to overcome the React hook useState async behavior?
- How to push to state in React Hooks?
- Array destructuring
- Eslint react-hooks/exhaustive derps recursion
- Webpack and External Libs: ProvidePlugin vs entry vs global import?
- can I wrap multiple varibles by one varible in reactjs
- Webpack - Error: Cannot define 'query' and multiple loaders in loaders list
- React- How to re-render view instead of appending it?
- Image violates the following Content Security Policy directive - Create React App
- typescript how to omit enum values
- React useState() - how to update objects
- How to mock react component and check if called with props
- Can't see that window.location has changed - react testing library
- How to hide MUI React ListItem?
- How to add props like fullWidth at particular width like 'sm' in Material UI React
- React useState throws error on Highcharts mouseOver
- Logout if token is expired
- Can't get data from simple json file in React
- Module parse failed: Unexpected token Reactjs?
- React router not redirecting on server
- how to properly format JSX in the new class (extends component) format
- I am having problem to fetch limited records for two different "basic" or "premium" subscribers and show records count in pagination in ReactJS
- PrimeReact TieredMenu - Uncaught TypeError: Cannot read property 'currentTarget' of undefined at TieredMenu.show (TieredMenu.js:84)
- concatenate components and text in reactjs
- ReactJS: Determining the index of an item in an array, that is passed from another file. (Using Ant Design)
- Deleting Specific Item From Array in React using Functional Components/Hooks
- CORS error on request, with headers and webpack-dev-server proxy configured
- React.js and PHP together?
- How to render svg string as image in React?
- Find object in array?
- How to select Multiple checkboxs values and Post to the server on Form Submission using React-Hooks
- How set Custom Input State Structure when User Inputs Something React js
- Change sort asc & desc onclick on two button to sort onclick on one button - React
- Tailwind CSS IntelliSense does not provide suggestions in a ReactJS project?
- How to import and export components using React + ES6 + webpack?
- Datepicker onChange issue React
- React Number Format unit test with isAllowed
- pass color as prop to child to change background react
- Ajax Call from React to a PHP file - don't know location
- Resize event in react
- clear interval from redux middleware
- Want to customise MUI - datatable Toolbar and positioning pagination top
- Why useState variable gets undefined inside try catch statement in an asynchrone function?
- Do you need action creators when working with Redux hooks?
- React js Router changes url but not loading page
- Find and push results in two objects being pushed into the array
- Javascript dynamically inserted later on: how to make it run?
- setState in React + TypeScript: FormData is not of type 'Blob'
- Problem Too many re-renders.Try to render components in connection with a button and state hooks
- Updating a list in React.js based on whether a new element was added or existing was edited
- React functional component re-renders with Redux
- Accessing Passport's req.user within React (ES6)? API call returns req.user as undefined
- How to loop component in reactjs?
- Invariant Violation: findComponentRoot when using Link & Tables
- How do you replace data multiple times with an array of keys using a react hook?
- Separate query from body in Axios request
- React - Upload avatar to firebase
- Markers not rendering using @react-google-maps/api
- Access generic data via passed key
- React JS - Error Cannot read property 'map' of undefined when rendering a Table
- How to display defaultValues with useFieldArray hook in controlled components in react-hook-forms
- Component render() triggered after history.push but page is blank
- How to debug/log useful information inside immer callback?
- How to get promises to work in IE10 with react
- .bind this in class method
- Getting a different port ERROR in the console while uploading image from the frontend using react js to the Mongo db
- Material UI, Warning <td> cannot appear as a child of <div>
- I want to get current page URL in React JSX
- How to stop user from accessing nodejs express routes
- Check Input as its being typed ReactJS
- not assignable to type '() => void' error when using React useMemo() with TypeScript?
- Configure production environment in a create-react-app(SyntaxError: Unexpected token < in JSON at position 0)
- await a `dispatch` in order to hide a modal box with `setState`
- React: Is it okay if useCallback returns a value, or is this a bad pattern?
- Pass parameters of a form to a REST API in React
- How to change two different .css class values with select option?
- remove autoprefixer warning in react 17.0.2
- Close modal after login React
- React + Meteor + Bootstrap Modal managing data
- I need to pause my custom timer and start from last value using rxjs operators
- Unnecessary rerenders with useContext
- Linking to a different react component on the same page
- Difference between event.target.value and event.currentTarget.value
- Can I use mocha to unit test react-templates in my ecmascript-6 app?
- Socket.io: Server side emit doesn't send if it's a certain value
- React Js Button Toggle/ Styled Components
- File type change (HTML input[type=file])
- jsPDF saving the file without extension when sent to nodejs/expressjs server
- React component wont re-render after onClick event
- Simplest way to adjust background color of a react-toastify Toast
- run a function in body of a component in react
- You should call navigate() in a React.useEffect(), not when your component is first rendered
- How to test react-toastify with jest and react-testing-library
- state variable has wrong value in functional component
- How to work around a slowdown from looping through images in React?
- history.push error with Typescript & React
- Can a component know its own DOM tree context?
- React: re render componet after button click
- Add column with a button which helps to route to a new page (when clicks) in material-table react
- es6 for loop not looping
- AWS S3 File Download from the client-side
- How to get the value of the span element with testid using react testing library?
- Testing functions containing Promise and FileReader() in Jest
- How to get second duplicate value rather than first value from JSON Array in React JS using lodash?
- react-sparklines remove startSpot
- NotFoundPage returned
- How to fix issue with state not equal to current state
- Why is the React portal a state?
- How to add padding within React Modal?
- Check whether a state variable includes a substring
- How to store URL Params, so browser remembers it when refresh or sending link to other browser
- Using CodePen front-end designs in reactjs app
- Y scroll event listener useEffect
- Error: React Module not found: Can't resolve '@atlaskit/util-data-test' when I update @atlaskit/util-data-test from 15.0.1 to 17.0.1
- "Parsing error: The type cast expression is expected to be wrapped with parenthesis" with React Hooks
- react js input doesn't allow writing
- How to display state object elements in another component?
- Getting null object on console for the first run in reactjs
- Routing to new page in react
- how to display cards on the same line using display flex?
- What is this css structure called?
- How to validate firebase user current password
- How to download excel in response from api react.js