In this article, I will show you about CRUD operation in React JS using Hooks and functional components and also will show how to implement it with the fetch() function using rest API. I will show you how to make insert, update, and delete operation functionality in React JS. We will also use the bootstrap and font awesome, using this we can create a beautiful UI for our operation.
In this We will discuses below point
- CRUD operation in React using functional component
- CRUD operation in React JS using Hooks
We can see in the below image that here we have created both HTML tables with delete and edit icons and options for adding a new customer.
OnClick of edit icon It will show a new row from where you can update the customer detail.
For performing the operation, we need to create a REST that will participate in CRUD operations , we are going to use the below customer API. we are going to create a simple customer page in which we will perform CRUD (Create, Read, Update and Delete) Operation using the below rest API.
1.GET http://restapi.adequateshop.com/api/Customer
Response:
[
{
"id": 121743,
"name": "dhiraj",
"email": "ds@gmail.com",
"location": "IND"
},
{
"id": 121742,
"name": "anjoo",
"email": "anu12345678@gmail.com",
"location": "pune"
},
{
"id": 121741,
"name": "Mike",
"email": "AADAD@gmail.com",
"location": "Paris"
},
{
"id": 121740,
"name": "Adil",
"email": "Adil@gmail.com",
"location": "Lahore"
},
{
"id": 121739,
"name": "dhiraj",
"email": "dhiqraLLjj435j@gmail.com",
"location": "IND"
},
{
"id": 121738,
"name": "snehal",
"email": "ahire@gmail.com",
"location": "sjhadjdwq"
},
{
"id": 121737,
"name": "dhiraj",
"email": "dhiraj27@gmail.com",
"location": "Inda"
},
{
"id": 121736,
"name": "dhiraj",
"email": "dhiraj26@gmail.com",
"location": "Inda"
},
{
"id": 121722,
"name": "guru",
"email": "guruswamy789@gmail.com",
"location": "tirupati"
},
{
"id": 121661,
"name": "sdasdw",
"email": "asdadw",
"location": "qdsadwq"
},
{
"id": 121660,
"name": "Mike",
"email": "mike456734@gmail.com",
"location": "Paris"
},
{
"id": 121659,
"name": "qdsadsa",
"email": "wdqdsad",
"location": "wqdsadwq"
},
{
"id": 121658,
"name": "sq",
"email": "sqqwdq",
"location": "dwqdq"
},
{
"id": 121657,
"name": "dwdwq",
"email": "dwqdsad",
"location": "dsqwqdwq"
},
{
"id": 121656,
"name": "ascas",
"email": "sadwqdsa",
"location": "dwqdsa"
},
{
"id": 121655,
"name": "abcabcsjk",
"email": "cbsajkbcsjk",
"location": "cbsajkcbsa"
},
{
"id": 121654,
"name": "acbcsbaj",
"email": "sbahjbscaj",
"location": "csbhjcsab"
},
{
"id": 121652,
"name": "qweqwe",
"email": "qweqwe",
"location": "dwqdwqsd"
},
{
"id": 121651,
"name": "asd",
"email": "asdhwudhu",
"location": "sjhadjdwq"
},
{
"id": 121650,
"name": "Dandy",
"email": "dandy2@fhu",
"location": "dsjdiwq"
}
]
2.POST http://restapi.adequateshop.com/api/Customer
Request Parameter
{
"name": "string",
"email": "string",
"location": "string"
}
3. PUT http://restapi.adequateshop.com/api/Customer/15624
Request Parameter
{
"id": 15624,
"name": "string",
"email": "string",
"location": "string"
}
4.DELETE http://restapi.adequateshop.com/api/Customer/15624
Step 1. CREATE NEW React js PROJECT
To create a new project, Open the terminal and run the below command.
npx create-react-app crud-app
Step 2. Install bootstrap CSS and font-awesome in our application using the below command for making beautiful UI.
npm install bootstrap –save
npm install –save font-awesome
Step 3. Create React Component in your project
Create a “components” folder inside the src folder in our react js application and add 3 files inside that folder.
- UserAction.js
- CreateCustomer.js
- CustomerList.js
Step 4. Create a Helper class file for calling API
Create a “httphelpers” folder inside the src folder in our react js application and restAPIHelper.js file inside that folder.
Paste the below code inside that folder
restAPIHelper.js
export const restAPIHelper = () => {
const callAPI = async (endpointurl, options = {}) => {
const defaultHTTPMethod = "GET"
const defaultHTTPHeaders = { //set defaultHeaders of Http request
"Content-Type": "application/json",
Accept: "application/json",
}
const controller = new AbortController() //using AbortController to cancel ongoing fetch requests
options.signal = controller.signal
options.method = options.method || defaultHTTPMethod
options.headers = options.headers
? { ...defaultHTTPHeaders, ...options.headers }
: defaultHTTPHeaders
options.body = JSON.stringify(options.body) || false
if (!options.body) delete options.body
setTimeout(() => { // cancel request if it will take more then 5s
controller.abort()
}, 5000)
try {
const apiResponse = await fetch(endpointurl, options)
return await apiResponse.json()
} catch (err) {
return err
}
}
//calling get API For fetching data
const get = (endpointurl, options = {}) => callAPI(endpointurl, options)
//Post to insert
const postCreate = (endpointurl, options) => {
options.method = "POST"
return callAPI(endpointurl, options)
}
//Put Api calling
const putUpdate = (endpointurl, options) => {
options.method = "PUT"
return callAPI(endpointurl, options)
}
//Delete Api calling
const deletedata = (endpointurl, options) => {
options.method = "DELETE"
return callAPI(endpointurl, options)
}
return {
get,
postCreate,
putUpdate,
deletedata,
}
}
Step 5. Write coding in the file to perform crud operation
UserAction.js
import React, { useState, useEffect } from "react"
import CreateAgent from "./CreateCustomer"
import UserList from "./CustomerList"
import 'bootstrap/dist/css/bootstrap.min.css';
import { restAPIHelper } from "../httphelpers/restAPIHelper"
const UserAction = () => {
const [customers, setcustomers] = useState(null)
const url = "http://restapi.adequateshop.com/api/Customer"
const api = restAPIHelper()
useEffect(() => {
getCustomers()
}, [])
const postCustomer = customer => {
api
.postCreate(`${url}`, { body: customer })
.then(res => getCustomers())
.catch(err => console.log(err))
}
const updateCustomer = (id, customer) => {
api
.putUpdate(`${url}/${id}`, { body: customer })
.then(res => getCustomers())
.catch(err => console.log(err))
}
const deleteCustomer = id => {
api
.deletedata(`${url}/${id}`, {})
.then(res => getCustomers())
.catch(err => console.log(err))
}
const getCustomers = () => {
api
.get(`${url}`)
.then(res => {
if(res)
{
setcustomers(res)
}
})
.catch(err => console.log(err))
}
if (!customers) return null
return (
<>
<h3>Add New Record</h3>
<table>
<tbody>
<tr>
<CreateAgent postCustomer={postCustomer} />
</tr>
</tbody>
</table>
<div className='container-fluid'>
<h3>All Tourist</h3>
<UserList
customers={customers}
setcustomers={setcustomers}
postCustomer={postCustomer}
updateCustomer={updateCustomer}
deleteCustomer={deleteCustomer}
/>
</div>
</>
)
}
export default UserAction
CustomerList.js
import React from "react"
import CreateCustomer from "./CreateCustomer"
import 'bootstrap/dist/css/bootstrap.min.css';
import 'font-awesome/css/font-awesome.min.css';
const CustomerList = ({ customers, postCustomer, updateCustomer, deleteCustomer }) => {
const showHideUpdateRow = id => {
const form = document.getElementsByClassName(`show-form-${id}`)
form[0].classList.toggle("hide-form")
}
const Row = ({ customer }) => {
return (
<>
<tr>
<td>{customer.name}</td>
<td>{customer.email}</td>
<td>{customer.location}</td>
<td>
<i className="fa fa-pencil-square fa-2x text-info" onClick={() => showHideUpdateRow(customer.id)}></i>
<i className="fa fa-trash fa-2x text-danger" onClick={() => deleteCustomer(customer.id)}></i>
</td>
</tr>
<tr className={`hide-form show-form-${customer.id}`}>
<CreateCustomer userData={customer} postCustomer={postCustomer} updateCustomer={updateCustomer} showHideUpdateRow={showHideUpdateRow} />
</tr>
</>
)
}
return (
<table className="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Location</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{customers && customers.map(u => <Row customer={u} key={u.id} />)}
</tbody>
</table>
)
}
export default CustomerList
CreateCustomer.js
import React, { useState } from "react"
import 'font-awesome/css/font-awesome.min.css';
import { faL } from "@fortawesome/free-solid-svg-icons";
const CreateCustomer= ({ userData = {}, postCustomer, updateCustomer,showHideUpdateRow }) => {
const [user, setUser] = useState({
id: userData.id ?? 0,
name: userData.name ?? "",
email: userData.email ?? "",
location: userData.location ?? "",
})
const handleValue = e => {
setUser({ ...user, [e.target.name]: e.target.value })
}
const submitUser = e => {
e.preventDefault()
debugger;
if (user.name === "" || user.email === "" || user.location === "") return
if (userData.id) {
debugger;
updateCustomer(userData.id, user)
} else {
postCustomer(user)
}
setUser({ ...user, "name": "", "email": "", "location": "" })
}
const hiderow = e => {
showHideUpdateRow(userData.id);
}
const isAdd = !userData.id ? true : false;
return (
<>
<td>
<input
type='text'
name='name'
className="form-control"
value={user.name}
placeholder='Name'
onChange={e => handleValue(e)}
/>
</td>
<td>
<input
type='email'
name='email'
className="form-control"
value={user.email}
placeholder='Email'
onChange={e => handleValue(e)}
/>
</td>
<td>
<input
type='text'
name='location'
className="form-control"
value={user.location}
placeholder='location..'
onChange={e => handleValue(e)}
/>
</td>
<td>
{isAdd ?
<input
className='btn btn-primary btnsubmit'
type='submit'
value={`${!userData.id ? "Add new user" : "Save user"}`}
onClick={submitUser}
/> :
<i className="fa fa-check fa-2x text-success" onClick={submitUser}></i>
}
{isAdd ? "" : <i className="fa fa-times fa-2x text-muted" onClick={hiderow}></i>}
</td>
</>
)
}
export default CreateCustomer
Step 6. Import UserAction.js component in App.js
App.js
import logo from './logo.svg';
import './App.css';
import UserAction from "./components/UserAction"
import 'bootstrap/dist/css/bootstrap.min.css';
function App() {
return (
<div className="container-fluid">
<main>
<UserAction />
</main>
</div>
);
}
export default App;
so, everything is done now run npm start command to see the result and perform crud operation.
Respond is a front-end library that is answerable for the UI. It is neither an entire system nor a language. It is an open-source JavaScript library for building the UI (UI) of an application.Respond is explanatory, adaptable, and simple to learn. Respond is kept up with by Facebook and a local area of individual engineers. At present, there is an enormous interest in React.js in the business.
Respond can be utilized for the advancement of single-page applications or versatile applications. For complex applications, React involves extra libraries for state the board, steering, and cooperation with an API.
Respond permits us to form complex UIs by composing a little piece of code. A secluded piece of code is called Component.
Essentials of React
You ought to know about HTML, CSS, and JavaScript essentials.You ought to likewise know about ES6.
The post React Js- Fetch data from API on button click appeared first on Software Development | Programming Tutorials.
Read More Articles
- Testing a react component using custom hooks with crud operations functions
- react-sortable-tree Crud Operation using hooks
- How to sync props to state using React hooks : setState()
- Equivalent to componentDidUpdate using React hooks
- React Hooks - using useState vs just variables
- Testing React Functional Component with Hooks using Jest
- TypeError dispatcher.useState is not a function when using React Hooks
- Proper way of using React hooks + WebSockets
- How to mock history.push with the new React Router Hooks using Jest
- Is there any way to see names of 'fields' in React multiple state with React DevTools when using 'useState' hooks
- How to prevent child component from re-rendering when using React hooks and memo?
- Using React Hooks To Update w/ Scroll
- Testing React components that fetches data using Hooks
- Warning when using react hooks in HoC
- How to clean up setInterval in useEffect using react hooks
- Updating an array in React using Hooks
- React-Router + React Hooks using withRouter
- how to set state array using react hooks
- Detect click outside React component using hooks
- UI not re-rendering on state update using React Hooks and form submission
- Why eslint-plugin-react-hooks doesn't warn when using react hooks conditionally?
- How to test custom hooks in React using JEST, Enzyme?
- Using ref with React Hooks in Ant design (antd) Table component with customized filters
- Update React Hooks State During Render Using useMemo
- How to fix 'no fallback UI was specified' in react i18next using hooks
- Loading React hooks using dynamic imports?
- getSnapshotBeforeUpdate using react hooks
- Using react hooks inside render prop function
- Using react context with react hooks in typescript
- React Native: Using Hooks in Flatlist
- Issue with Menu.Item NavLink always active Semantic UI React
- react-router-dom Link on click close bootstrap modal window
- $.ajax like function for React js and Angular js?
- wrapper.find is not a function
- Manual DOM updates and React Component Rendering using forceUpdate()
- How to apply an id attribute to a child element of a ReactJS component?
- How to add active class to clicked item in ReactJS
- Update a state variable only on loading the page for the first time in react js
- I am trying to use a tool tip but not sure how to make the trigger work
- How to create an admin route and another private route for registered users with a normal route?
- how to stop a timer in setInterval by click then resume by click again?
- Video element didn't show up after successfully getting local stream WebRTC
- Can't use react state inside a socketio on event callback function
- React: How can we know that all component has been mounted/rendered after setState()?
- How to create a dinamic list which has an item description that shows only on clicking the item?
- How to create a show more/less button with ReactJS to adjust the size of a div?
- Session lost when refresh the page (Next, react, isomorphism)
- How to use Ant Design LocaleProvider with React-Boilerplate
- In React how can I append values to functional state when it is a dependency of useEffect without triggering another API call?
- Function not returning value in react JSX
- Error: Super expression must either be null or a function
- React.js A valid React element (or null) must be returned
- Can only update a mounted or mounting component. findless error
- The prop `history` is marked as required in `Router`, but its value is `undefined`. in Router
- Focus input after redux dispatch finished
- React TypeScript: How to get form values, and response codes using fetch
- ReactJS component PropTypes - specify a function type with a set number parameters
- Map stops iterating after first iteration in React
- Can't access express route?
- React history push not rendering the component
- How can I put the data inside the MuiDataTable with these codes?
- How to test immutability and if reducer if pure function in Jest
- Using React, how do I make the value of my variable dynamic?
- How can I load only part of a Redux Store in a React Application
- ReactJS: setState from outside
- Dynamically Cover Image with Rectangle in HTML/CSS
- ReactJS passing arrow function as a prop
- Is it valid to increment a state object value inside setState(); without cloning the object?
- How to pass the username to the sibling component?
- Cannot read property 'questions' of undefined
- useEffect called multiple times when using <Redirect> or history.push()
- How to load external libraries into jsdom for testing reactjs modules with enzyme full rendering
- What is the equivalent value of document.getElementById().setCustomValidity() in Reactjs
- How to fix '_this4.props.handleExport' error in React
- Comma operator in TypeScript JSX expressions
- How to iterate over array by key name and if keys are empty include them in loop js
- React JS (Admin on Rest) error when API call
- how to calculate estimated time accuracy
- TypeScript Interfaces: Property 'A' does not exist on type 'B | null'
- Full Calendar Prev - Next Button in React
- Problems displaying new div when onMouseOver event fires
- How to make placeholder still visible?
- Multiple ajax calls in loop inside ajax success
- How do I reuse a method to handle multiple, different refs in React?
- TypeError: vis_network__WEBPACK_IMPORTED_MODULE_3__.DataSet is not a constructor
- How can I correctly declare an arrow function?
- Navlink from react-router-dom Home always active
- How to center an image in ReactJS using css
- React The function called in onSubmit in a form is not run
- How to override previous classes with next classes in tailwind?
- how to render to home after login in react js?
- Issue to submit CSV file to DB via POST Axios & React-Final-Form
- Does it matter if a function within a React component is not pure?
- Passing arguments to top level fields from within a Relay container
- Why is my react component not updating with state updates?
- What is BetterJsPop error on chrome?
- React Typescript - variable null check ignored and sends error
- mongodb update Unexpected token
- React props id binding to onClick in a stateless component
- How to put <Route children={({match})} => ... > in Jsx fragment. React router dom v6
- React signup page syntax error at return of render function
- Edit user information in React
- react: Should I put all side effect logic inside useEffect
- I am not able to get jwt token from cookies while authorization some pages.?
- Creating a document every time someone signs up in firebase
- How do I fix CORS issue in Fetch API
- How to enable absolute path aliases with eslint import plugin in a typescript react project?
- Toggle class only on one element, react js
- Using react I am trying to have a button's color change when a a value is updated onclick
- Using Redux to display a notification in response to a network request
- React-Redux: Insert Data in DB
- jsx print components via array
- Best ways to update state array object using React Hooks?
- Checkbox onchange function is always undefined in React component class
- The request is missing a Valid API Key while using Youtube Data API v3
- How to show links only on App component not on child component in React using React Router?
- Execute Function when a State Variable Changes inside of a useEffect() Hook
- How Can I check if both Arrays inside this.state contains same value?
- Handling errors with React and Formik
- How to pass a default value to an input in React (using props)
- mapping a new array in react
- How to limit props.children.some to image type only?
- TypeError: match.loader.options.plugins is not a function
- Elements overlapping other in react
- How to pass props from React Router 4 to a Container?
- What is a good URI design for creating a new resource?
- this.state on setState callback function after this.setState()
- MUI Autocomplete with Select All
- Using ReactJs to fetch data from an API but getting completely blank page with no errors
- How to change a useState's object value in react?
- Not able to move div using mousemove in react
- Reactjs npm test: Jest encountered an unexpected token
- Troubles with d3.js + react.js and passing data
- Array getting undefined on state change on Redux
- Multiple path names for a same component in Reach Router
- React setState not executing within firestore add document promise resolve
- useEffect is not removing events correctly
- Reusable React Map Method for Different Selected Arrays
- Updating state with nested array of objects
- Handsontable & React
- How prevent duplicated list object in react redux
- How to know the useful height of an iOS device in React Native?
- Force a disabled MI TextField to be clickable
- How to this setState to set a value from function?
- 'Parsing error: Unexpected token' error for an arrow function?
- React Native refresh content when user hits back button - using Hooks
- Good way to interact between different and same levels of depth (nested) in ReactJS ('States' + Hooks)
- ReactJS add callback function to children component
- Can't fetch data with Axios and React, getting an Promise and Undefined
- Component Style Update Not Waiting on setTimeOut Function
- How to mock plain object's dependency when unit testing with jest?
- Remove listener in React.js
- Quill undefined when uploading a file from local machine
- How to get a variable back from a called component
- Is it possible to override material-ui components default props?
- Initial state undefined in redux connected react app
- Pagination in GatsbyJS blog
- Reducers are gone after attempting to implement redux-persist
- React hooks: call component as function vs render as element
- React Hook using Controller for a custom Input
- Use React component in InfoWindow content
- Cannot change primary button color with LESS (ant.design)
- Rerender only specific Child Components in JSX map function
- GatsbyImage not working in production site (Pulling data from WP CMS)
- How to transpile styled components into an NPM package?
- How to disable a link in reactjs?
- How to select multiple row in Table row ?Using(ctrl+click) and (Shift+click) in react js
- Javascript insert Object value into another Object with same key
- Best way to restrict page access?
- How to solve "termsOfUse must be a boolean type, but the final value was: "on"." using Ionic, React, Yup and Resolvers
- React 16.3+ correct way to fire onChange from state change
- Can't display my data in a react-bootstrap-table
- Adding an onClick event to an svg element in a java script class
- TypeError: Cannot read property 'id' of undefined react map function
- React getInitialState not working
- Typescript onChange not passing event.Name to dynamically update props
- Replace search current page contents with search contents
- useCallback dependency array defeats the purpose of preventing re-renders when updating an array
- In react, how can I determine the width of a container before rendering a child image?
- React : render over an associative array
- JSX not being rendered
- Is there a way to set default parameters for multiple function without have to copy paste it
- Get child property in React
- How to append inputs with formik in react
- Dynamically load from API SVG via hooks ReactJs
- this.props.xyz is not a function when child calls parent
- Invalid Hook calls in React.JS
- npx create-react-app running with old version
- Property is missing in Interface when passed to parent
- Image parsing, formatting, rendering in REACT
- Show a react-placeholder skeleton until a image loaded completely in a page
- Firebase firestore WEB v.9 retrieve data ID-s from collection where that current user ID contains
- How to change MaterialUI onPageChange actions for Table Pagination
- State updating in redux
- How to construct JSX using a loop
- How to extract and set value to Switch at same time ? React
- React Router v6 - Navigate/Redirect to blanc page
- ReactJS - how to style the parent?
- axios http always returns with empty data
- How do you aggregate values from a child component's states in React?