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 can I add a script function to React
- Force component to wait for redux state update
- Right align menu options with material-ui
- React-Native-Navigation get rid of constructor?
- React useState hook issue on updating real time data inside MQTT communication
- How to override a React component's CSS using emotion CSS?
- Buttons do not work Uncaught TyperError: onUpdateCartQty is not a function
- Firebase + Next.js serverless, on GCP - How to manage staging, production + local
- react js - announcements.map is not a function
- JS Add to array with Spread Operator if non-NULL - Expression Syntax
- mousemove and mouseover is not working for the last data in d3 chart
- Create-React-App: .env file doesn't parse correctly
- React Testing Library: Objects are not valid as a React child
- Adding new element to array with useState React
- Jest/Enzyme test React component with async/await method in try/catch
- Why's there discrepancies between file uploading via Postman and via the browser?
- React Js create option list from array
- Get data from express with fetch
- Reactjs function not being called
- Wrapping React's setState function in ES8's async/await
- How to get updated state value in React useEffect hook
- embedded function in .map to access mapped information
- setState is not updating in my other method
- Calling a method on Parent Component from Child Component
- Material UI position Box element to bottom of parent
- Sorting and Filtering React - Context
- Typescript error: Property 'classes' is missing in type
- Typescript for Facebook React
- React. How to call method of specific subchild in component tree
- What does {...props} in this React Component mean?
- React cannot set div to take 100% of screen height
- Ref error in React.JS Ref - createRef, useRef, and using Refs
- Caret, tilde, or fixed package.json for large production app?
- How to scroll to the top of the page after a route change, but retain the scroll position when going back?
- Get page location with React Router 4 and Hash routing
- javascript iterative logical XOR for array of objects?
- react redux re-render not triggered by state-change
- What is the correct way to pass parameters to a React-query useQuery method that uses Axios
- How to determine which icon is clicked in a menu with Material-UI icons
- ReactJs error: semicolon expected after render
- How do I make this into 4 column in one row and also responsive as well?
- Inject reducer for on demand component which was not in the store or combined reducers initially
- Where are the React Flow types defined?
- HTML React set cursor to different contenteditable div
- I cannot upload files to the directory I specified using node js multer
- ReactJS image not displaying when src is passed in from parent
- react warning Expected to return a value at the end of arrow function array-callback-return
- React WebWorker using fat arrow syntax insted of class syntax
- How to lazy load multiple components at a same time
- Call react function from JQ function
- Multiple states in one React component?
- input pattern='[a-zA-Z]' is not working in React application
- React.js - Show/Hide dynamically generated elements from component
- How to apply styles to a function in React js using hooks
- Gatsby activeClassName not working preview
- Formik - Update initial values after API call
- How do I get type checking to work with React forwardRef
- How to open Drop Down only if in input entered required keyword?
- Share auth between django and react
- How to make the cursor in draftjs editor to remain where it was when changing and receiving focus?
- Animation not triggering when using material UI
- Callback function don't set state so component try to re-render with empty values and throw error
- TypeError: render is not a function updateContextConsumer
- createSelector of reselect: does it do deep comparison for nested object?
- React wont update state on useEffect
- How to remove the outline for the cell in table when you click the cell?
- Babel configuration with decorators & class properties not working
- React Formik - not submitting form
- Pressing enter to submit form in react-testing-library does not work
- useeffect proper use with async function
- Why is myreact component not displaying on mobile
- Display modal window only once with React Hooks
- ReactJS Output won't render to HTML, but works in console log
- React warning React Hook useEffect has a missing dependency when the deps are []
- TypeScript: Interface cannot simultaneously extends two types
- REACT JS: Map over an array of objects to render in JSX
- Using React, click the first input show the second input, how to auto focus to the second input?
- How to display response error when it exists but is unknown until received
- just select one checkbox in reactjs
- ReactJS dynamic child with keys
- Passing multiple params in Redux Toolkit's createAsyncThunk
- How can I set up state to allow one child component to render another
- Toggling the value when click using React Context
- Node Express app.get(*) req.url is always /favion.ico
- What can be my problem with my client api?
- Filter an object from an array in react
- use same function for different buttons
- React empty JSX tables
- Axios Api calls in Heroku
- React JS - Change parent state on child click, map not iterable
- File not found error when trying to 'fetch' json in React App
- Redux: Where to place "dumb" handlers?
- Why is my react component not rendering only when using routes? react-router-domV.6
- Error: Objects are not valid as a React child If you meant to render a collection of children, use an array instead
- How to fix "TypeError: Cannot read property 'map' of undefined" in JavaScript?
- React - Multiple images upload timing is wrong (Firebase Firestore and Storage)
- Updating the added data using the same form | Reactjs
- Passing correct properties to popup notification
- React Hooks won't work on Firebase Cloud Functions Error: Invariant Violation: Invalid hook call
- How to write test with swr
- Testing React components with Jest & Enzyme: where to test whether component props were given
- How to pass mouse events between overlapping components in ReactJS
- How to filter and get the properties inside an object array
- React JS how to pass values between pages using session storage
- "Good" way how to update state (from its previous value) in React
- Changing scope of promise returned in a conditional import to a different variable in React
- React behavior triggers all buttons on render
- Pass props locally with React-Router's #createElement
- Error rewriting as a React Functional Component in Typescript: Property 'forceUpdateHandler' does not exist on type 'MutableRefObject<Spinner | null>'
- Redux relation between component, container and mapDispatchToProps,mapDispatchToProps
- nth-child(odd) affecting all children instead of odd
- conditionally render child component following onChange event
- Using Material-UI Box Component with the Drawer Compoment
- How to change property of SlateJS node element onChange?
- Why do my react-native components overlap
- Why ``module build failed`` error when trying to use fontawesom icons in my react project?
- What is the right construction to print this JSON data in React?
- Make the dumb components a tad smarter
- Can't get proper location state in React Router if location is added in Routes component
- How to add type FunctionComponent to React functional component using the "function" syntax and not "const"?
- How to properly update props in redux store?
- When exactly is state available in React?
- Replace String in content
- Getting this typescript error: Unsafe member access [key] on an any value
- How to pass ref to children of children using array of refs React?
- Why is my React production app not working on mobile browsers?
- Peer react-dom@15.6.2 wants react@^15.6.2
- implement the onSnapshot function for getting realtime updates in reactjs code
- React Native Firebase V9.1.1 Order By Date Key
- How can I use "Enter" button to setState to my component
- Btn classes is not clickable in react.js?
- How to wait until React component completely finished updating in Jest and/or Enzyme?
- Console output does not show number of elements of array. Array Elements not accessible in code
- Edit text onClick in react
- How to remove options in react quill
- Typescript - make an optional property required when another property is present
- How do you import a javascript package from a cdn/script tag in React?
- React-Router: Print page title in component?
- Server side React Router user authentication
- How does KonvaJS handle drawing on the canvas
- React JS: Looping through an array and creating a div each 3 items
- How to make Material UI List to open just one List Item?
- Rewrite a function to find an object by a matching id inside an array, update a value and set a react state
- ReactJS w/ Inertia - calling onClick function multiple times
- How to concatenate date and time
- Passed function as prop and is undefined
- React, not able to not run the logic inside useEffect after url change
- How to use ReactHowler with a playlist
- how to customize react material ui next component
- I want to put Component in TableBody tag
- Scrolling horizontal menu while scrolling in React JS app
- Typescript error - Unable to find react context in wrapped child component
- how to return one index object of an array (instead of the entire array)
- How do I make a Grid component clickable to check/uncheck checkbox?
- How do I write a delete handler function with React Hooks?
- Password States are reacting one character late
- TypeError: Cannot read property 'value' of undefined - REACTJS
- React js css stylesheet applied to more than one component
- react-three-fiber change model function in canvas
- How to solve TypeError: environment.teardown is not a function
- Submit and close modal window. React React-Hook-Form Typescript
- how can I put a document.addEventListener("scroll") in other file to call it in my component?
- React routing: Switch not working as expected with id_token
- React / React Router - Treat <a> tags like <Link> tags
- When upgrading from Hyperloop to Hyperstack, is "opal_hot_reloader" gem still necessary?
- Dynamically creating an element on which the react app mounts
- React Router V6 IIS deployment Refresh not work
- React-Router: How to redirect Route to another url conditionally?
- convert reducer from react redux to hooks
- Detect Route Change with react-router