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
- Ternary operation not working on button click in reactJS?
- how to implement createAsyncThunk
- How to dynamically show the number of button clicks in React
- React Redux HOC
- Microservices UI Frontend with Java and ReactJS Server Side Rendering
- Module not found: 'cldr' in ... \globalize\dist\globalize
- Bootstrap responsive menu - tabs into select list
- react-three-fiber: Rotate tetrahedron "face down"
- Prevent going back conditionally with react-router-dom 5
- Unable to render Table in Reactjs
- create-react-app - How to bundle JS files
- Pass value from one component to another values in array ReactJS
- How do I add these dependencies?
- passing props to the component conditionally in reactjs
- Understanding state input in react
- Antd file upload validation in Reactjs
- Set bootstrap switch component to 'checked' if mode is Dark
- How to keep sync validation with Redux-form v6 while implementing custom onBlur?
- How can I add React web components to a parent component dynamically?
- React State Management: Context API as global store
- How to Parse XML using axios in react js
- Infinite loop in ComponentDidUpdate
- Type error thrown on element
- How to set column width to my excel sheet using reactjs
- How do i implement dark mode using states and save the setting to my localstorage?
- axios.post not returning data from server: "Cannot destructure property 'data' of '(intermediate value)' as it is undefined"
- Clicking option in a custom dropdown [React component with outside click function & array of refs]
- Fowarded ref is null
- How to center button overlaying image with React Bootstrap?
- Increase map max zoom level
- react-dates onDatesChange startDate and endDate are null, DayPickerRangeController
- React Next.js not calling useEffect hook in production app
- Is it true that for 0.3 or 0.6 seconds of sliding a panel away using React / Redux, we'd already have to dispatch two actions to handle it?
- Extend Functional Components in ReactJS
- How to call state from base class in ReactJS?
- Routes being cached by service worker in react
- I have 2 components and I want a 3rd component to show animation while waiting for the 2nd one to load images
- React Slick prev and next methods throw an error
- React Bootstrap V3, make row have height of max height component in two column view
- Using reducer state inside useEffect
- How to get user informations from Firebase after page reloaded in Nuxt js project?
- How do I scroll up and down a SideBar rather than the whole window?
- React - Error: App(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null
- Restyling Bootstrap Components with React/Typescript styled components
- Keyboard changes all components placement in react native
- Redirect in Reat JS
- How to replace existing data (key/value pair) instead of appending to an array via immutable js?
- Set the style of ::after to be equal to the style of the selected element
- Json server Data is not Fetching Correctly in react
- Dynamic material ui drop menu
- Using Promise from Reactjs-promise returns an error
- Postgres UPDATE inserted value instead of all columns
- How do I change the theme in an AnyChart React tag cloud?
- Spread Operator not copying results in React
- why console.log("hello) is printing six times in React hooks
- Is this an example of destructuring assignment?
- Return an object inside useEffect() and access it outside in React (after having assigned a state)
- Enforce jsx to start on new line if jsx is multiline
- ReactJS: Unable to parse through a 2d array outside async function
- show data from object on click
- Regex to validate username in Javascript
- Using express post with react
- How can I use dynamic css variables in react?
- React: Can't create li element because Promise(<pending>);
- How to make my react component rerender when I submit a form into firestore
- Unit test method that calls clearInterval with Jest and Enzyme on React
- Detect multiple clicks on a field in React JS
- How to use next() function in Next JS API like Express JS?
- react-styled-flexboxgrid different config for different viewport
- Dynamically changing react-modal content
- Property 'spacing' does not exist on type 'DefaultTheme'
- React replace li bullet with icon
- error: attempted to update component that has already been unmounted (or failed to mount)
- The pros/cons of React class property initializers
- How to include custom script files in Create-react-app application
- What is the different bethween using `children` elements vs using `render` func in React Router?
- How to style the React google map marker using the given image file
- On clicking material-ui autocomplete blank page is opening in react js
- How to access global scope from cloudinary react widget
- How to add properties to an object, where it defined in a function?
- Play only one song at a time (React)
- Serve React app via custom Express server while keeping automatic updates during development
- OnScroll event firing without scrolling - Reactjs
- Access object attributes and display component in a new page
- Cannot get Ant design Table cell to have reference to dynamic # of columns
- Sliding CSS Animation on hover in React element
- Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application
- How to Use componentDidMount() in Functional Component to execute a function
- React Route does not work with nested URLs
- React Testing Library - "messageParent" can only be used inside a worker
- React hide header component for some routes
- Transform a SPFX TS without JS framework to a React TS
- webpack/react/babel doesn't compile JSX
- What is the difference between mapDispatchToProps and matchDispatchToProps
- Is there a good way to use React hooks inside a callback or render prop?
- Failed to compile ./src/App.js Attempted import error: 'UserProvider' is not exported from './model/UserContext'
- How to re-render component after fetch request and state change?
- How to write 2 fetch method for contact API and Message API in reactjs?
- onSubmit function is not invoked even after clicking on submit button
- Is there any way to see names of 'fields' in React multiple state with React DevTools when using 'useState' hooks
- How do I save my data from my POST request, as a variable, to use in my GET request?
- Auto Scroll Horizontal Mui TabList on Drag with react-beautiful-dnd
- onmouseover show Message on React
- React router, link to component and show in url
- How to show a component on click in React?
- How to Translate string in array of objects with using react-i18next Without a functional component of a react
- Can you pass different Material-ui icons as props?
- how we can sort table as costume ordered values?
- Error using react-update
- React Component not correctly reloading on stateChange
- Typescript with Redux, how to use connect without re-declaring action definition?
- Scroll when hover arrow - like amazon website
- Django with NextJS integration
- Sass relative import with webpack
- Where should I set localStorage in redux toolkit
- React native - which files to include in version control after installing native-base?
- page not loading react js
- How to download file without opening in new tab in reactjs
- NextJS + React context: How to load data?
- gutenburg run js function on post save
- React and redux toolkit: how to add reducer that gets data from a drag and drop event
- How to add custom `PNG` image to material ui icon
- React-Redux rendering components twice on screen when redux state changes
- Correctly positioning a Modal without restructuring code React
- Cannot Open Dev Menu on Xiaomi Devices
- React - Uncaught Error: Target container is not a DOM element
- Validating a child input type file with react-hook-form and Yup
- I can't get this array to filter out on click in React
- how to open desktop folder in electronjs
- Replace image element with inline svg in React
- How to use Nodejs package in Reactjs Application?
- Too many re-renders. React limits the number of renders to prevent an infinite loop. and
- React Native Navigation override goBack() of header back button in Stack Navigator
- React Troubles when trying to update states from props
- How to deploy react project to ftp using Bitbucket Pipelines?
- Data is not being stored in redux store
- How can I make my React child components render even if a prop is missing
- How can I link an input to a react router link
- How to Create a grid of desired Size by using react-data-grid in reactjs?
- Mock Postman request into Axios?
- React router dom routes are returning blank pages
- How to convert this create store with thunk to a promise based?
- TypeScript interface signature for the onClick event in ReactJS
- How to trigger React TransitionGroup and Transition to animate onLoad
- setState value used in componentDidMount is not reflected in Enzyme test
- ReactJs how to render pair-value of assoc array
- Styled Component Semantic kit ( Form . Input )
- I cant use bootstrap modals in a map function
- If list contains more than 25 elements, take only the newest 25 elements at a time
- How can I force update React.memo child component?
- React.js calling a button click from a different button
- Extend prototype using decorator
- Webpack: Need an appropriate loader to handle this file type error
- Firebase Cross-platform issue - .setAsync() is setting in 2 path destinations instead of just one
- Cant disable X-Powered-By: Express
- Ternary not updating view in React
- React: Passing values to a context returns: 'TypeError: Right side of assignment cannot be destructured'
- How can I access ...pageProbs that I passed to a Component in _app.js
- What is relationship between Express routes and client routes in NextJS?
- React: can we impot only selected functionality from npm module while installing using webpack or somthing else?
- Integrating ReactJS SPA with Django
- How to have a separator between arabic numbers in javascript?
- My request is responding with a 404 error yet it is posted as supposed
- How to import a stylesheet from external source in react?
- self navigate react page goes into infinite loop
- how to 'inject' confirm event into react-select?
- React hooks: Can't update state inside function component
- Next.js Module parse failed: Unexpected character '�' (1:0)
- Please include phone-type-formatter.{country}.js lib
- How do I play audio from an array of objects in React.js