In this post, we are going to discuss how to do a simple CRUD Operation in react js using a bootstrap simple HTML table.
CRUD Meaning
CRUD word that comes from the world of computer programming and directs to the four operations that are considered essential to implement a storage application i.e create, read, update and delete.
React JS CRUD example with Rest API
So let’s start React JS CRUD Example — step by step
Step 1
Create react js app using the below command
npx create-react-app crud-app
Step 2
Install bootstrap CSS in our project using the below command
npm install bootstrap –save
Step 3: Rest API for performing Crud operation
1.GET http://restapi.adequateshop.com/api/Tourist
Return list of tourists in the organization, we are going to use this API for binding our table list.
{
"page": 1,
"per_page": 10,
"totalrecord": 8508,
"total_pages": 851,
"data": [
{
"id": 116597,
"tourist_name": "Johnyt",
"tourist_email": "j56644@gmail.com",
"tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
"tourist_location": "Usa",
"createdat": "2022-05-05T09:32:28.8548478"
},
{
"id": 116595,
"tourist_name": "Testing",
"tourist_email": "pppppppp12121@gmail.com",
"tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
"tourist_location": "INDIA",
"createdat": "2022-05-05T09:28:33.2964054"
},
{
"id": 116592,
"tourist_name": "John",
"tourist_email": "joaa44@gmail.com",
"tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
"tourist_location": "Usa",
"createdat": "2022-05-05T09:09:33.4510789"
},
{
"id": 116589,
"tourist_name": "John",
"tourist_email": "johnhj@gmail.com",
"tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
"tourist_location": "Usa",
"createdat": "2022-05-05T09:03:48.6965879"
},
{
"id": 116588,
"tourist_name": "John",
"tourist_email": "jo7898944@gmail.com",
"tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
"tourist_location": "Usa",
"createdat": "2022-05-05T09:03:24.405684"
},
{
"id": 116584,
"tourist_name": "Mikelion",
"tourist_email": "mikepp12388888li88on@gmail.com",
"tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
"tourist_location": "lionParis",
"createdat": "2022-05-05T08:35:46.0262257"
},
{
"id": 116583,
"tourist_name": "Mikelion",
"tourist_email": "mike12388888li88on@gmail.com",
"tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
"tourist_location": "lionParis",
"createdat": "2022-05-05T08:26:27.837058"
},
{
"id": 116582,
"tourist_name": "testing12121",
"tourist_email": "testing121212@gmail.com",
"tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
"tourist_location": "India",
"createdat": "2022-05-05T08:21:24.4612766"
},
{
"id": 116580,
"tourist_name": "Mike",
"tourist_email": "vrushali1212121@gmail.com",
"tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
"tourist_location": "Paris",
"createdat": "2022-05-05T08:20:33.1709003"
},
{
"id": 116575,
"tourist_name": "hello",
"tourist_email": "abcd9839@gmail.com",
"tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
"tourist_location": "Usa",
"createdat": "2022-05-05T07:30:12.3328337"
}
]
}
2.POST http://restapi.adequateshop.com/api/Tourist
This endpoint is used For making the entry in the database, you need to pass the 3 parameters i.e tourist_name, tourist_email, and tourist_location in the request body.
Request
{
"tourist_name": "Test user",
"tourist_email": "testuser123@gmail.com",
"tourist_location": "USA"
}
API Response
{
"$id": "1",
"id": 15863,
"tourist_name": "Test user",
"tourist_email": "testuser123@gmail.com",
"tourist_profilepicture": "http://restapi.adequateshop.com/Media//Images/userimageicon.png",
"tourist_location": "USA",
"createdat": "2022-01-03T07:53:37.626145Z"
}
3. PUT http://restapi.adequateshop.com/api/Tourist/15863
This endpoint is a PUT endpoint and we use that endpoint for updating the record.
API Request
{
"id": 15863,
"tourist_name": "Test Update",
"tourist_email": "testuser123@gmail.com",
"tourist_location": "Paris"
}
API Response
{
"$id": "1",
"id": 15863,
"tourist_name": "Test Update",
"tourist_email": "mike123@gmail.com",
"tourist_profilepicture": "http://restapi.adequateshop.com/Media//images/userimageicon.png",
"tourist_location": "Paris",
"createdat": "2022-01-03T07:53:37.626145"
}
4.DELETE http://restapi.adequateshop.com/api/Tourist/15863
This endpoint is used for deleting the record in the database.
Step 5-Create a “httphelpers” folder inside the src folder in our react js project. and add a file inside that folder with the name “restHelper.js”.
Copy and paste the below
restHelper.js
export const restHelper = () => {
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)
debugger;
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,
}
}
I have created the helper class httphelpers/restHelper.js, which will work as a global helper class and we can utilize that helper in another class or component. using that helper class we will make the different HTTP requests in our application.
Step 4-Create a “components” folder inside the src folder in our react js project.
Step 4-Right-Click “components” folder ->New File and create the component and I’ll call it Touristtable.js, Crudtourists.js, and Addtourist.js
Touristtable.js
we have created this component, for binding the tourists to the table.
import React from "react"
import Form from "./Addtourist"
import 'bootstrap/dist/css/bootstrap.min.css';
const Touristtable = ({ tourists, postTourist, updateTourist, deleteTourist }) => {
debugger;
const showUpdateUser = id => {
const form = document.getElementsByClassName(`show-form-${id}`)
form[0].classList.toggle("hide-form")
}
const Row = ({ tourist }) => {
return (
<>
<div className='row'>
<div className='col-sm-2'>{tourist.tourist_name}</div>
<div className='col-sm-3'>{tourist.tourist_email}</div>
<div className='col-sm-3'>{tourist.tourist_location}</div>
<div className='col-sm-4 buttons'>
<button className="btn btn-info" onClick={() => showUpdateUser(tourist.id)}>Update</button>
<button className="btn btn-danger" onClick={() => deleteTourist(tourist.id)}>delete</button>
</div>
</div>
<div className={`hide-form show-form-${tourist.id}`}>
<Form userData={tourist} postTourist={postTourist} updateTourist={updateTourist} />
</div>
</>
)
}
return (
<div className='table'>
<div className='row'>
<div className='col-sm-2'>Name</div>
<div className='col-sm-3'>Email</div>
<div className='col-sm-3'>Location</div>
<div className='col-sm-4'>Actions</div>
</div>
<div className='rows'>
{tourists && tourists.map(u => <Row tourist={u} key={u.id} />)}
</div>
</div>
)
}
export default Touristtable
Crudtourists.js
we have created this component for rendering Touristtable.js component and showing the list to the user.
import React, { useState, useEffect } from "react"
import Form from "./Addtourist"
import Tablelist from "./Touristtable"
import 'bootstrap/dist/css/bootstrap.min.css';
import { restHelper } from "../httphelpers/restHelper"
const Crudtourists = () => {
const [tourists, settourists] = useState(null)
const url = "http://restapi.adequateshop.com/api/Tourist"
const api = restHelper()
useEffect(() => {
gettourists()
}, [])
const postTourist = tourist => {
api
.postCreate(`${url}`, { body: tourist })
.then(res => gettourists())
.catch(err => console.log(err))
}
const updateTourist = (id, tourist) => {
api
.putUpdate(`${url}/${id}`, { body: tourist })
.then(res => gettourists())
.catch(err => console.log(err))
}
const deleteTourist = id => {
api
.deletedata(`${url}/${id}`, {})
.then(res => gettourists())
.catch(err => console.log(err))
}
const gettourists = () => {
api
.get(`${url}`)
.then(res => {
if(res && res.data)
{
settourists(res.data)
}
})
.catch(err => console.log(err))
}
if (!tourists) return null
return (
<>
<h3>New user</h3>
<Form postUser={postTourist} />
<div className='container-fluid'>
<h3>All users</h3>
<Tablelist
tourists={tourists}
settourists={settourists}
postTourist={postTourist}
updateTourist={updateTourist}
deleteTourist={deleteTourist}
/>
</div>
</>
)
}
export default Crudtourists
Addtourist.js
we have created this component for adding the tourist information to the database.
import React, { useState } from "react"
const Addtourist = ({ userData = {}, postUser, updateTourist }) => {
const [user, setUser] = useState({
id:userData.id ?? 0,
tourist_name: userData.tourist_name ?? "",
tourist_email: userData.tourist_email ?? "",
tourist_location: userData.tourist_location ?? "",
})
const handleValue = e => {
setUser({ ...user, [e.target.name]: e.target.value })
}
const submitUser = e => {
e.preventDefault()
debugger;
if (user.tourist_name === "" || user.tourist_email === "" || user.tourist_location === "") return
if (userData.id) {
debugger;
updateTourist(userData.id, user)
} else {
postUser(user)
}
setUser({ ...user, "tourist_name": "","tourist_email": "","tourist_location": "" })
}
return (
<form onSubmit={submitUser} className='form-inline'>
<div className="form-group">
<input
type='text'
name='tourist_name'
className="form-control"
value={user.tourist_name}
placeholder='Name'
onChange={e => handleValue(e)}
/>
</div>
<div className="form-group">
<input
type='email'
name='tourist_email'
className="form-control"
value={user.tourist_email}
placeholder='Email'
onChange={e => handleValue(e)}
/>
</div>
<div className="form-group">
<input
type='text'
name='tourist_location'
className="form-control"
value={user.tourist_location}
placeholder='location..'
onChange={e => handleValue(e)}
/>
</div>
<input
className='btn btn-primary btnsubmit'
type='submit'
value={`${!userData.id ? "Add new user" : "Save user"}`}
/>
</form>
)
}
export default Addtourist
Now open App.js file and import Crudtourists.js
import logo from './logo.svg';
import './App.css';
import CrudData from "./components/Crudtourists"
import 'bootstrap/dist/css/bootstrap.min.css';
function App() {
return (
<div className="container-fluid">
<main>
<CrudData />
</main>
</div>
);
}
export default App;
Now let’s run project using below command
npm start
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:
The post React Js- Fetch data from API using hooks appeared first on Software Development | Programming Tutorials.
Read More Articles
- 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
- CORS error while consuming calling REST API with React
- Trouble with simple example of React Hooks useCallback
- How to authenticate users with Social Login (Facebook, Google) in a REST API backend with Spring Boot (separate React Frontend)
- Pagination in React with REST API
- Deploying React App with Spring Boot REST API in AWS BeanStalk
- React Higher Order Component explained with Context API example
- 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
- Build a CRUD App with React Hooks and the Context API
- How to implement pagination in React JS with REST API
- Simple React example with state not working
- How to send FormData attribute with an array of strings from React Client to Django + Django Rest Framework API
- I have spent the last 8 hours trying to pass a simple JSON object with some data from an api through my express backend to one of my react components
- Correct way to display formatted JSON data from rest api with React
- react redux asyc tasks with rest api
- Pulling Data From Node.js Rest Api Into React with axios
- Trying to use React Spring with Semantic UI React, simple example
- React JS with Spring boot API REST
- ReactTable - react component with REST API Call
- Can't get React Router to work with this simple example
- react get data from rest api with axios and and useEffect redering empty array plus array with data
- connecting react frontend with node js rest api
- HTTP ERROR 405 when deploying React frontend with Spring boot REST API backend
- How to send current date time to Rest Api with put request in react js?
- Rest API get call - put data in array - with typescript and react
- Wordpress to React REST API : Objects are not valid as a React child (found: object with keys {rendered})
- Fetching 'title' from WP REST API with React
- React simple REST API using basic authentication
- SpringBoot with React - Rest API clashes with React Routes on refresh
- Is constant re-rendering making my react dapp slow? Or is it a problem with web3?
- How to implement adding custom js code snippet feature in React SPA?
- Inserting HTML fragments without an element container in React
- Initializing a text input default value with data coming from state supplies the text input with old state data
- Pass mobx store and props to function
- How do I deliver my bundle.js file with my html in GO using gorilla/mux
- React Tiny Virtual List - Scroll to bottom?
- How to assign csv data to state in react?
- How to return multiple components in render function?
- How to handle and validate sessions between the backend and the frontend
- use react in views folder in mvc express project
- Styles not applying to the react component
- Async test to throw with Jest
- [React]Jest SyntaxError: Unexpected token import
- React Router in meteor.startup.js (meteor top-level)
- Webpack & Typescript image import
- Test suite failed to run. Invariant Violation: _registerComponent(...): Target container is not a DOM element
- i can't delete component in CRUD app on button click
- React | webpack | getting process.env.NODE_ENV== undefined on Azure
- Blank screen in reackhooks Home page with Maximum update depth exceeded. This can happen when a component calls setState
- Material-ui: Reset slider to default values of min and max
- React - require some aid with saving data to a table
- useRef to create a cellEditor in ag-grid in React
- How can I separate the JSX mapping logic from the mapped array containing components with props?
- Meteor flow router and getting params of route in a react component
- "Uncaught SyntaxError: Unexpected token l in JSON at position 0", but still works, why?
- How to stop Timer when button is clicked in React?
- Webpack config - Adding another entry file
- How to get static routing after a dynamic routing in Next.js
- How do I limit fetch calls made to an endpoint service so that no more than 10 calls per second are made?
- Get error "TypeError: Cannot read property 'object' of undefined" when import "React-Magnific-Popup" package
- Renaming keys in an object using reduce method in JS
- How to detach mock function from the react component's prototype so that will not affect other test?
- Issue with mapping through the data - React
- Karma js will not serve picture files
- Call function only in specific state in React with Hooks
- ReactJS app is unable to fetch data using REST API call
- How to automate firebase deploy in reactjs?
- electron-builder not working for production due to path
- MUI Autocomplete, scroll with keyboard need highlight
- Unable to render out array in React using Array.map
- useRef Typescript error: Property 'current' does not exist on type 'HTMLElement'
- How to hover over one chart to display a vertical line and tooltip on all charts in D3.js?
- Trouble getting an Authentication Token using Axios for React
- Routes not working as desired in React JS
- React-like conditional rendering in Flutter
- MUI - dark theme doesn't change anything
- React + Redux - Call a method of a component wrapped for the Redux Provider
- react-admin: Filter with SelectInput shows wrong values
- What is difference between reactstrap and react-bootstrap?
- React: this.setState is not a function
- Seamlessly switch between a text element and a text input in Material UI
- React onClientClick not firing my function handler
- Access React context outside of component
- error: Cannot set properties of undefined when setting the value of nested object
- Can't pass value from parent to child and child to parent properly
- React router render causing unmount
- React component (react-redux props) keeps rerendering with React.memo()
- How to grab ASP.NET Web Api token (login) from a JS fetch and save token
- Highcharts React: Menu button doesn´t change from "view full screen" to "exit full screen" when fullscreen mode is on
- React JS Reducer - Not able to do anything with the returned payload, only able to print
- Unable to pass data between components in react
- How to create Checkboxes with CheckAll checkbox in react hooks?
- ag-grid prevent rowDrop
- Refresh the page after adding the item to the array
- React re-render anything anytime
- Redux store doesn't update on first button click
- How to customize components in the admin area of SilverStripe?
- Add Sass (.scss) to ejected create-react-app config
- Redux - What is immutable state change for reducer?
- Handling input change depending on the number of key value pairs
- 'TypeError: NetworkError when attempting to fetch resource' on form submit ReactJS
- React / MobX: Store values are undefined?
- Antd clear form after submit in reactjs
- React Web// iOS like select dropdown on mobile
- TypeError: doc is not a function at addSubCollectionDocument
- Reactjs custom element rendering by string
- How to use React hooks with similar variables?
- Chrome Dev Tools Shows all useState hooks with the name 'State'
- How to show row index in grid js using react js
- How can I dynamically display what appears in the modal
- How to use apollo-client API directly to query with fetchPolicy='cache-and-network'?
- React Testing Library: Match Number of Buttons
- Next.js render video only on desktop: useEffect can't perform a React state update on an unmounted component
- Error Cannot find module 'perf_hooks' when creating site with React-static
- Flex cards in 5 column
- React hooks, setting state on select
- Deleting item from state array in react
- Rendering grid in React using lodash
- React - Using state in component by useContext
- Cors Error with AWS Lambda and .Net Core WebAPI
- Unable to see toast in cypress
- Assign a const variable inside a map function
- How react functional component can use object variable which declared behind the usage? (include example)
- service worker notificationclick event doesn't focus or open my website in tab
- React redux current user param gets too late to use
- Requiring modules from requirejs (with babeljs plugin) in es6 scripts
- Reselect error: Selector creators expect all input-selectors to be functions
- How to post new object to the existing json (clientside ReactJS + server side NodeJS and Express)
- How to clear selected value from dynamic select dropdown in react?
- React.js component run error. Uncaught TypeError: this.state.setState is not a function
- React Router Redirect state is undefined when used in Protected Route
- Form inline not working as expected with React-Bootstrap
- Why isn't my array copying without reference in React?
- Each record in table should have a unique `key` prop,or set `rowKey` to an unique primary key
- How would I my component work inside another component without repeating code?
- How can I do top level await
- typescript: Better way to type optional without default value?
- Does "webpack-dev-server"' compile my files to disk?
- How to fix missing dependency warning when using useEffect React Hook? I am using nextjs app
- ScrollToBottom function not working in React hook reactjs
- React.js custom hook testing using Jest
- how to ready react app with webpack
- field required based on value of another field - formik, yup
- How to store value from callback function in react state? (Google Maps)
- How can i ignore react warnings? (Not Native app)
- React Redux how to pass data from input to rest api
- TextField in MenuItem causes nextFocus.getAttribute is not a function
- How to implement AddAdiditions in React Sematic UI using Hooks?
- How can i fixed the npm run deploy problem
- How to tell webpack dev server to serve index.html for any route
- Unable to map inside an async function
- How to use "this" keyword inside a fetch API call result
- Rerender React component with new AJAX query parameter values
- How do I update my NavBar once a user is logged-in (from 'log in' to 'profile') using React & Firebase?
- Material-UI: TablePagination hide next and prev
- Is there a way to solve any jest package issues?
- How to improve this JS code to look more elegant
- Why does Typescript think my enum is undefined?
- React ambiguous error messaging: "Check the render method of `Constructor`."
- Page wont refresh when using React Link and passing state
- How to hide the tick marks of the axis in react-chartjs-2
- Fetching User Data From ID: WP REST API
- Conditional Rendering on Server Side
- Mocking axios.post response triggered by button in react component
- React Hook useEffect has a missing dependency. Why am I getting this error when nothing is broken?
- Conditions in reducers
- ReactTs how to execute a get request a lot of times on component
- React event: get Key AND prevent event propagation
- Docker, script seems to build and run properly, but cant connect on localhost
- How to get event from components to container in React Redux
- set default value for select menu from mongodb
- Webpack cannot resolve file or dic
- FirebaseErrorr: Missing or insufficient permissions happens, When trying to get snapShot
- REACT: How to update the list after click button EDIT?
- ReactJS JSX Syntax for If-Else
- Error :: DELETE http://localhost:3000/users/todo/delete/undefined 404 (Not Found)
- Trying to display burger menu dropdown behind navbar
- After updating state, using set, the state still has empty array
- Use dynamic routes while maintaining existing file structure with Next.js
- How to turn try catch function into promise function
- React CSSTransition
- I Want To Fetch Only data With A Specific Field Value On Firebase
- ReactJS overriding or editing context along the hierarchy
- React: Load Content from Server and Render to React
- Using an async function on useEffect that has as an argument a State that's also async setted
- React onClick event is not firing on bootstrap dropdown menu
- Redux - why loading everything in state at root
- React : Hide menu on all sub pages
- React updating irregularly
- React Passing state to sibling component and up to parent class
- How can I disable underline in Material-UI without removing the selection in Autocomplete?
- Show A Div Section From A Selected Option - Stateless Components
- access root element of react component
- CRA + Inversify @inject Module parse failed: Unexpected character '@'
- How to remove TextField state
- React-Router using <Router> gives :- Cannot read property 'location' of undefined
- Why does gatsby develop work well, but gatsby build doesn't work? - ERROR #95313
- JSX condition that does not work with React
- Need help printing out a list from db