In this article, we will learn how to create a CRUD operation in React js using Axios and with a real-time rest API. We have already learned how to create CRUD operations Using the fetch function now in this post we will perform the insert update, and delete example operation using Axios.
After the awesome response to a published article by me: Simple React.js CRUD Example With Rest API to help beginners, I decided to rewrite the article with step by step approach using Axios, since it is the latest topic in the IT industry today.
I have written this article focusing on newbie developers so they can understand the basics of the concept of Axios class component, and calling rest API using Axios.
First, we will Fetch data from API and display it in the table using Axios in a class component and then we will perform insert, update and delete operations.
Crud operations in React Js with Axios and Rest API
Before starting creating the application let’s have a look at the rest API part first. We are going to use TravelAgent table for performing CRUD Operations. Here is the rest API for performing the CRUD operation.
1.GET http://restapi.adequateshop.com/api/TravelAgent
[
{
"id": 121212,
"agent_name": "yeem soni",
"agent_email": "Mayank77@gmail.c",
"agent_location": "USA",
"createdat": "2022-05-18T11:19:00.2704177"
},
{
"id": 121211,
"agent_name": "nanoi soni",
"agent_email": "Mayank77@gmail.",
"agent_location": "USA",
"createdat": "2022-05-18T11:19:00.0125955"
}
{
"id": 121206,
"agent_name": "kil soni",
"agent_email": "Mayank77@g",
"agent_location": "USA",
"createdat": "2022-05-18T11:18:58.1125961"
},
{
"id": 121205,
"agent_name": "tony soni",
"agent_email": "Mayank77@",
"agent_location": "USA",
"createdat": "2022-05-18T11:18:57.683823"
},
{
"id": 121204,
"agent_name": "southy soni",
"agent_email": "Mayank77",
"agent_location": "USA",
"createdat": "2022-05-18T11:18:57.0549635"
},
{
"id": 121203,
"agent_name": "dublin soni",
"agent_email": "Mayank78",
"agent_location": "USA",
"createdat": "2022-05-18T11:18:53.6840485"
}
]
2.POST http://restapi.adequateshop.com/api/TravelAgent
Request Parameter
{
"agent_name": "string",
"agent_email": "string",
"agent_location": "string"
}
3. PUT http://restapi.adequateshop.com/api/TravelAgent/12514
Request Parameter
{
"id": 12514,
"agent_name": "string",
"agent_email": "string",
"agent_location": "string"
}
4.DELETE http://restapi.adequateshop.com/api/TravelAgent/12514
Step 1. Create React js App
Now, let’s create a React app using the below command.
npx create-react-app crud-app
Step 2. Create React Component
Create a “components” folder inside the src folder in our react js application and add 3 files inside that folder.
- CrudOpertaion.js
- CreateAgent.js
- GetAgent.js
Step 3. Install bootstrap in our project
Now, let’s install bootstrap to create a lovely UI for our application.
npm install react-bootstrap bootstrap
If you get any errors while installing bootstrap then try the below command
npm install react-bootstrap –legacy-peer-deps
import bootstrap in index.js
Step 4. Install Axios library in our project
Axios is the latest promise-based JavaScript HTTP client library that works asynchronously and allows our app to make HTTP calls and consume REST API very efficiently.
npm install axios –save axios
Step 5. Do coding in the file to perform our operation
CrudOpertaion.js
import React, { Component } from 'react';
import { Container, Button } from 'react-bootstrap';
import AgentList from './GetAgent';
import CreateAgent from './CreateAgent';
import axios from 'axios';
const apiUrl = 'http://192.168.1.105:234/';
class CrudOpertaion extends Component {
constructor(props) {
super(props);
this.initialState = {
id: '',
agent_name: '',
agent_email: '',
agent_location: '',
}
this.state = {
isAddagent: false,
error: null,
response: {},
agentData: {},
isEditagent: false,
isAgentDetails: true,
}
this.onCreateAgent = this.onCreateAgent.bind(this);
}
onCreate() {
this.setState({ isAddagent: true });
this.setState({ isEditagent: false });
this.setState({ isAgentDetails: false });
this.setState({ agentData: this.initialState });
}
onDetails() {
this.setState({ isAgentDetails: true });
this.setState({ isAddagent: false });
this.setState({ isEditagent: false });
}
onCreateAgent(data) {
this.setState({ isAddagent: true });
this.setState({ isAgentDetails: true });
debugger;
if (this.state.isEditagent)
{
axios.put(apiUrl + 'api/TravelAgent/'+data.id, data).then(result => {
alert('Updated successfully!');
this.setState({
response: result.data,
isAddagent: false,
isEditagent: false
})
});
} else {
axios.post(apiUrl + 'api/TravelAgent', data).then(result => {
alert('Created successfully!');
this.setState({
response: result,
isAddagent: false,
isEditagent: false
})
});
}
}
editAgent = agentId => {
debugger;
this.setState({ isAgentDetails: false });
axios.get(apiUrl + "api/TravelAgent/" + agentId).then(result => {
this.setState({
isEditagent: true,
isAddagent: true,
agentData: result.data
});
},
(error) => {
this.setState({ error });
}
)
}
render() {
let userForm;
debugger;
if (this.state.isAddagent || this.state.isEditagent) {
userForm = <CreateAgent onCreateAgent={this.onCreateAgent} agent={this.state.agentData} />
}
return (
<div className="App">
<Container>
<h1 style={{ textAlign: 'center' }}>CURD operation in React</h1>
<hr></hr>
{!this.state.isAgentDetails && <Button variant="primary" style={{ float: 'left', marginBottom: '15px' }} onClick={() => this.onDetails()}>Go Back Agent Details</Button>}
{!this.state.isAddagent && <Button variant="primary" style={{ float: 'left', marginBottom: '15px' }} onClick={() => this.onCreate()}>Add Agent</Button>}
<br></br>
{!this.state.isAddagent && <AgentList editAgent={this.editAgent} />}
{userForm}
</Container>
</div>
);
}
}
export default CrudOpertaion;
import { Table, Button } from 'react-bootstrap';
import axios from 'axios';
import React from 'react';
const apiUrl = 'http://restapi.adequateshop.com';
class AgentList 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 });
}
)
}
deleteAgent(agentId) {
const { agents } = this.state;
axios.delete(apiUrl + '/api/TravelAgent/' + agentId).then(result => {
alert('deleted successfully');
this.setState({
response: result,
agents: agents.filter(agent => agent.id !== agentId)
});
});
}
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>
<th>Action</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>
<td>
<Button variant="info" onClick={() => this.props.editAgent(agent.id)}>Edit</Button>
<Button variant="danger" onClick={() => this.deleteAgent(agent.id)}>Delete</Button>
</td>
</tr>
))}
</tbody>
</Table>
</div>
)
}
}
}
export default AgentList;
import React from 'react';
import { Row, Form, Col, Button } from 'react-bootstrap';
class CreateAgent extends React.Component {
constructor(props) {
super(props);
debugger;
this.initialState = {
id: '',
agent_name: '',
agent_email: '',
agent_location: '',
}
if (props.agent.id) {
this.state = props.agent
} else {
this.state = this.initialState;
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const name = event.target.name;
const value = event.target.value;
this.setState({
[name]: value
})
}
handleSubmit(event) {
event.preventDefault();
this.props.onCreateAgent(this.state);
this.setState(this.initialState);
}
render() {
let pageHeading;
let btnText;
if (this.state.id) {
pageHeading = <h2>Edit Agent Detail</h2>
btnText = <b>Update</b>
} else {
pageHeading = <h2>Add Agent</h2>
btnText = <b>Save</b>
}
return (
<div>
<b> {pageHeading}</b>
<Row>
<Col sm={12}>
<Form onSubmit={this.handleSubmit}>
<Form.Group controlId="FirstName">
<Form.Label>First Name</Form.Label>
<Form.Control
type="text"
name="agent_name"
value={this.state.agent_name}
onChange={this.handleChange}
placeholder="Name" />
</Form.Group>
<Form.Group controlId="EmailId">
<Form.Label>Agent email</Form.Label>
<Form.Control
type="text"
name="agent_email"
value={this.state.agent_email}
onChange={this.handleChange}
placeholder="email" />
</Form.Group>
<Form.Group controlId="agent_location">
<Form.Label>Address</Form.Label>
<Form.Control
type="text"
name="agent_location"
value={this.state.agent_location}
onChange={this.handleChange}
placeholder="Address" />
</Form.Group>
<Form.Group>
<Form.Control type="hidden" name="AgentId" value={this.state.id} />
<Button variant="success" type="submit">{btnText}</Button>
</Form.Group>
</Form>
</Col>
</Row>
</div>
)
}
}
export default CreateAgent;
Step 6. Import component in App.js
import logo from './logo.svg';
import './App.css';
import Opertaion from "./components/CrudOpertaion"
function App() {
return (
<div className="container-fluid">
<Opertaion/>
</div>
);
}
export default App;
so, our coding part is completed, and run npm start command perform to see the result.
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 React, a part is alluded to as a segregated piece of code which can be reused in either module. The React application contains a root part in which other subcomponents are incorporated; for instance – in a solitary page, the application is partitioned into 3 sections – Header, Main Content, and Footer. Along these lines, there is a solitary App Component having 3 subcomponents – Header Component, MainContent Component, and Footer Component.
There are 2 kinds of parts in React.js Stateless Functional Component and Stateful Class Component
Stateless Functional Component
This kind of part incorporates basic JavaScript capacities. These parts incorporate unchanging properties, i.e., the incentive for properties can’t be changed. We want to utilize Hooks (will be examined in the following article) to accomplish usefulness for making changes in properties utilizing JS. A utilitarian part is utilized mostly for UI.
Stateful Class Component
The Class part is ES6 classes which broaden the Component class from React library. The class part should incorporate the render technique which brings HTML back.
The post React Js- Fetch data from API on button click appeared first on Software Development | Programming Tutorials.
Read More Articles
- react get data from rest api with axios and and useEffect redering empty array plus array with data
- Using different API url for development and production with React and axios
- React axios with PHP Rest API , how to write the baseurl
- Fill context from REST API and use it in a React component with useEffect and useContext
- How to integrate axios api in react js with async and await using react hooks
- Show Api errors with React final form and Axios
- SetState with react hook and redux after async call to axios API
- Build a CRUD App with React Hooks and the Context API
- Failed call to Deezer API with React and axios
- How to upload file to Django rest framework API using Axios and react hook form?
- I want a simple authentication with bearer token and rest api which should be stored in local storage and be refresh in given time in REACT
- Rest API React and AXIOS in functional component
- Filtering through API with React and Axios
- Pulling Data From Node.js Rest Api Into React with axios
- How to pass open weather API data to React front-end with serverless function and axios
- how to get spesific data from api with axios and react js?
- how to write one GET api call using axios instance with and without params in React JS
- Rest API get call - put data in array - with typescript and react
- Calling api in react with axios and search but don't know how to do it
- How to make react router work with static assets, html5 mode, history API and nested routes?
- CORS error while consuming calling REST API with React
- CORS Issue with React app and Laravel API
- react native post form data with object and file in it using axios
- Paginate date-specific results from an API with React and Redux
- How to test snapshots with Jest and new React lazy 16.6 API
- How to use Django User Groups and Permissions on a React Frontend with Django Rest Framework
- Standalone REST API & Standalone React SPA vs Django and React combined
- Post an object with fetch using react js and express API server
- How to send CSRF Cookie from React to Django Rest Framework with Axios
- React and Axios GET request issue with Safari on MacOs and iOs
- How to track , on url change in React app
- Why is console log returning a Proxy Object?
- How do I mock a async function in a component when testing reactjs with enzyme and jest?
- Vite and Sendbird does not works
- Why is react-markdown outputting code blocks instead of HTM:
- React router private route is accessing routes that it shouldn't access
- Refactoring a class based component to hooks (gapi API)
- react redux with axios api calls
- Secure pages in sign in/up AWS Cognito React
- Using the show route in react + rails
- Set a placeholder value to Select component Material UI v1.0.0-beta.24
- Spring Security always redirecting me to the default login page
- Component can't catch error from function passed as a prop
- 404 Not Found Nginx Error on Deployment of React App Build
- How to use react Hook state variables without a callback function?
- Testing Library - Test onChange not called
- React init state array with init function that repeatedly calls setState
- How can I disable a particular button after click, in a buttons array?
- How to add scoped css in react?
- material ui <ExpansionPanel> onChange pass variable
- Replace BrowserRouter with HashRouter
- How to load Material UI Theme based on Redux Store entry
- React-d3 Chart Not Showing
- react-router-dom redirect not redirecting to the component I want it to but it is redirecting to a different path
- How to make CORS Request
- React Remote Console Logging
- How to prefilled data in form and the form is editable by using react functional component
- React select v2 on space press selects first value
- Uncaught (in promise) SyntaxError: Unexpected end of JSON input at AddAutor.js:78
- React state assignment before setting state
- Why aren't {...props} necessary when passing them to a component in a router in React?
- How to use useSprings?
- react js with mysql, how to use select with args?
- Showing warning for filter method in React js
- Use NTLM authentication with Axios
- Issues with setting value with useState()
- React Virtualized List with AutoSizer - vertical scrollbar does not appear
- React updating irregularly
- function gives me TypeError: Cannot read property 'resize' of undefined
- React (Performance): How to prevent unwanted rendering on each state change?
- Insert value into a array with hooks (REACT)
- React-Redux mapStateToProps with dynamic (uid based) path
- Convert moment.js to date-fns
- Catch 401 and render a message on the same component
- Get data of selected node in antd tree
- Define array of object as state variables on ECMA6/react
- React Redux filter actions (generic sorting example)
- sort table based on a certain column
- Does reactJS has filters as we have in angularJS.
- Show limited portion of array based on currentPage value using slice()
- ReactJs. Get children component
- Looping over an array of objects and showing values based on static keys defined javascript
- How to import image into React from public folder through a json file
- Activating 2 different calls on react onClick
- Dynamically generated object property undefined
- Is passing the _setTitle method with the props the way to go?
- Warning: Expected `onClick` listener to be a function, instead got a value of `boolean` type
- How do I dynamically position a SVG ontop of another SVG in React.sj?
- Best practice for defining state in function component React
- How to create shared component in React correctly?
- Dynamic Input field in React Formik
- React TDD - How do I get inner text?
- How to pass a custom style to MUI V5 styled component?
- Can I download an image if it's in base64 format?
- Uploading a file in React redux firebase
- How to make a circle checkbox with MUI?
- How to pass multiple properties down 2 levels of components while keeping their names in React?
- Localhost windows10 took to loong to respond
- react app is running development mode on Heroku?
- how to use materialize-css with react and keeping the size of installed components of materialize-css to be minimum
- Calling an onclick event from a different Component
- Can't get React Grid Ag-grid to automatically resize itself at screen width
- How to import react modules from an HTML file with no npm/webpack
- How to process JSON fields with lodash map/countBy/groupBy?
- How to overlay the left sidebar and push the other components to right?
- using state value in state data for apex charts within react app
- How to render component with for loops in react
- Request fails while having a bearer token in the header of the request
- How to type props for Material UI ListItem?
- React accessing to array's values using dynamic naming for the variables
- TypeError: tableData.map is not a function
- Rails: Webpacker::Manifest::MissingEntryError in Home#index
- A way to call React component's method from outside (with it's state and props)
- Change react props within component as optimization
- React - Add class along with Dynamic class
- Get dimensions of image with React
- TypeError: jquery__WEBPACK_IMPORTED_MODULE_5___default(...)(...).isotope is not a function
- How do I deploy a React app and a Rails API to Heroku?
- Trying lessening the amount of functions i need to write to set state to the props of this elements size
- Using JSON with Material UI nested menus
- How to upload files from ReactJS to Express endpoint
- react js how to import only the required function from a file and not the all functions
- Lazy load components in react
- State in another component is not updated with useEffect after initial render, but it is with button onClick
- How to set callback function as prop for react-paginate and TypeScript?
- MERN Stack - Express and React on same port?
- looking for a way to pass the token to apollo-client via cookies not localstorage
- Text Area in material-ui
- Can somebody help me in understanding what is happening in this piece of code
- Extend the React Router of exist application on fly
- How to access current location in reducer (redux-router)?
- Stubbing method in same file using Sinon
- Trying to test FormControlLabel in enzyme won't trigger click when simulate
- Flow throws an error on React element creation in a generic function
- Button Transition Effect using class not working accordingly
- react-scripts variable is not defined, but webpack working fine
- ReactJS: How to refresh component without 1 click delay
- React overwriting state variables in an object
- Redux #subscribe vs. #mapStateToProps
- How can I functionally autofill props for a React Component?
- Protected route is inaccessible due to props being passed
- How to use React's context API outside of react's component scope : ReactJS
- React onClick inside .map then change data in another sibling component
- Map over API data in React
- Calling Meteor methods in React components
- Removing function on server which delete array with bunch IDs
- npm compiling warning (Parsing error: Unexpected token, expected ";" )
- I can't display the items from the API in react App
- How to use state information with className in react?
- Property *** does not exist on type 'ExoticComponent<any>
- How to detect rerenders in React JS correctly?
- Not able to connect AdSense to Gatsby blog
- Mutating the DOM in React
- How to navigate between screens in react without usage of libraries like react router
- I am passing the state to a function component via history (react-router-dom) but it says the state is 'undefined'
- enzyme test multiple render methods within same component
- Using Grommet with ReactJS webpack and scss import Issue
- Reactjs - Replacing array value from another
- How to prevent user from selecting date above end date in react-dates
- Issue with Graphql in React fetching with a nested object - Object is undefined
- how test a component inside the _app from NextJS?
- How to design state based on useReducer
- React-hook-form with material-ui does not keep value change in onBlur() method
- How to generate UUIDs in JS or React?
- How to show reminder only on specific date in React
- Adding the properties to the window object and using it before the import of components
- React - online not rendering
- A generic change handler for text inputs using Typescript/React with dictionary type
- VS Code Absolute Paths auto-complete & click-to-see-definition using js/tsconfig.json
- React useContext not causing a rerender
- Custom hook with useRef and useEffect
- How to show Vertical Progress Bar in react-transition-group with animation
- How to use react-datepicker with redux form?
- useEffect on async operation
- Wrap a problematic npm package, while maintaining type information
- ReactJs: need to change Card into another card onClick
- Why to use separate CSS files for components in React.js
- Adding full screen background in react-slick carousel
- Styled Components Color Picker not showing
- To continuously try to 'GET' the api. if it fails due to network error
- I'm using React-Bootstrap. The e.preventDefault() is not working
- Is there any way to use event object inside React's componentDidMount method?
- Updating a page at refresh AND change of state
- Using JQuery plugins that transform the DOM in React Components?
- Create 2 Dimensional Array from Object with same key
- Disable submit button if no change is done to the form
- React router redirect outside of route component
- REACT / AG-GRID: Dynamically setting columnDefs after retrieving data
- How to store and retrieve images of type data:image/jpeg;base64?
- Element type is invalid on routes react-router-redux
- Possible to render Material elements within material-table?
- React how to combine data from multiple API and render it
- react-transition-group/react-router jumps to top of window on route change
- How to disable a button when state changes in React
- Datefield holding its value, but not displaying it
- Using a higher order component with multiple Draft.js editors in single page
- <select> Initial value is showing undefined (React js)
- Is it possible to call dom element methods like focus() without using a ref? (Stateless Component Functions)
- How to set default input for input keypress?
- component update doesn't see the latest var value