Untitled Document
Untitled Document
First, ensure that you have React and Bootstrap (for UI components) installed. If not, you
can add them using npm or yarn:
bash
Copy code
npm install react-bootstrap bootstrap
Add the Bootstrap CSS to your src/index.js (or src/App.js depending on your setup):
javascript
Copy code
import 'bootstrap/dist/css/bootstrap.min.css';
Here is a breakdown of how to integrate each CRUD operation with the mock API:
In the CrudApp component, you're using state to manage form data (name, father name,
mother name, email, and DOB) and also the list of users. You'll perform CRUD operations on
this data by calling the mock API.
javascript
Copy code
componentDidMount() {
// Fetch users when the component mounts
this.fetchUsers();
}
javascript
Copy code
handleAddUser = () => {
const { userName, userFatherName, userMotherName, userEmail,
userDOB, editId } = this.state;
1. When the "Edit" button is clicked, populate the form with the existing user’s data.
2. Send a PUT request to update the user's data on the API.
javascript
Copy code
edit = (user) => {
this.setState({
userName: user.userName,
userFatherName: user.userFatherName,
userMotherName: user.userMotherName,
userEmail: user.userEmail,
userDOB: user.userDOB,
editId: user.id, // Set the ID of the user being edited
});
};
handleUpdateUser = () => {
const { userName, userFatherName, userMotherName, userEmail,
userDOB, editId } = this.state;
fetch(`https://676a3a7a863eaa5ac0ddb69d.mockapi.io/users/${editId}`,
{
method: "PUT", // PUT request to update an existing
user
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(updatedUser), // Send updated user
data
})
.then((response) => response.json())
.then(() => {
this.fetchUsers(); // Re-fetch user list after update
this.setState({
userName: "",
userFatherName: "",
userMotherName: "",
userEmail: "",
userDOB: "",
editId: null, // Reset state after update
});
});
}
};
To delete a user:
1. When the "Delete" button is clicked, send a DELETE request to the API to remove
the user.
javascript
Copy code
delete = (id) => {
fetch(`https://676a3a7a863eaa5ac0ddb69d.mockapi.io/users/${id}`,
{
method: "DELETE", // DELETE request to remove user
})
.then(() => {
this.fetchUsers(); // Re-fetch the list of users after
deletion
});
};
Here's how the entire code will look after integrating the mock API for CRUD operations:
javascript
Copy code
import React, { Component } from 'react';
import './CrudApp.css';
import Table from 'react-bootstrap/Table';
componentDidMount() {
this.fetchUsers();
}
fetchUsers = () => {
fetch("https://676a3a7a863eaa5ac0ddb69d.mockapi.io/users")
.then((response) => response.json())
.then((data) => this.setState({ users: data }));
};
handleAddUser = () => {
const { userName, userFatherName, userMotherName, userEmail,
userDOB, editId } = this.state;
handleUpdateUser = () => {
const { userName, userFatherName, userMotherName, userEmail,
userDOB, editId } = this.state;
fetch(`https://676a3a7a863eaa5ac0ddb69d.mockapi.io/users/${editId}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(updatedUser),
})
.then((response) => response.json())
.then(() => {
this.fetchUsers();
this.setState({
userName: "",
userFatherName: "",
userMotherName: "",
userEmail: "",
userDOB: "",
editId: null,
});
});
}
};
render() {
const { users, userName, userFatherName, userMotherName,
userEmail, userDOB } = this.state;
return (
<div className="container">
<div className="form-container">
<h2 className="form-heading">Registration Form</h2>
<input
type="text"
name="userName"
placeholder="Your Name"
value={userName}
onChange={this.inputChange}
className="form-field-input"
/>
<br />
<input
type="text"
name="userFatherName"
placeholder="Father Name"
value={userFatherName}
onChange={this.inputChange}
className="form-field-input"
/>
<br />
<input
type="text"
name="userMotherName"
placeholder="Mother Name"
value={userMotherName}
onChange={this.inputChange}
className="form-field-input"
/>
<br />
<input
type="email"
name="userEmail"
placeholder="Your Email"
value={userEmail}
onChange={this.inputChange}
className="form-field-input"
/>
<br />
<input
type="date"
name="userDOB"
value={userDOB}
onChange={this.inputChange}
className="form-field-input"
/>
<br />
{this.state.editId ? (
<button type="submit" onClick={this.handleUpdateUser}
className="form-field-input btn bg-primary">
Update User
</button>
) : (
<button type="submit" onClick={this.handleAddUser}
className="form-field-input btn bg-success">
Add User
</button>
)}
</div>
<Table className="table-dark mx-auto mt-5" bordered hover>
<thead>
<tr>
<th>Id</th>
<th>Your Name</th>
<th>Father Name</th>
<th>Mother Name</th>
<th>Your Email</th>
<th>D.O.B.</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id}>
<td>{user.id}</td>
<td>{user.userName}</td>
<td>{user.userFatherName}</td>
<td>{user.userMotherName}</td>
<td>{user.userEmail}</td>
<td>{user.userDOB}</td>
<td>
<button onClick={() => this.edit(user)}
className="btn bg-primary mx-1">
Edit
</button>
<button onClick={() => this.delete(user.id)}
className="btn bg-danger mx-1">
Delete
</button>
</td>
</tr>
))}
</tbody>
</Table>
</div>
);
}
}
Key Takeaways:
● The API is integrated into the application using the fetch method for CRUD
operations.
● GET: Fetches users from the API when the component mounts and when a CRUD
operation happens.
● POST: Adds new users by sending a POST request with the user data.
● PUT: Updates users using the user ID with a PUT request.
● DELETE: Deletes users by sending a DELETE request using the user ID.
Explain
explain code in one by one line
ChatGPT said:
ChatGPT
Sure! Let’s break down the code line by line to explain how each part of it works.
● fetchUsers = () => {...}: Defines a method that fetches the user data from
the mock API.
● fetch("https://676a3a7a863eaa5ac0ddb69d.mockapi.io/users"):
Makes a GET request to the mock API to retrieve the list of users.
● .then((response) => response.json()): Converts the API response into
JSON format.
● .then((data) => this.setState({ users: data })): Once the data is
fetched, it updates the component’s state with the list of users.
● handleAddUser = () => {...}: Defines the method for adding a new user
when the form is submitted.
● const { ... } = this.state;: Destructures the state to get the form fields
(userName, userFatherName, etc.).
● if (userName && userFatherName && ... && editId == null): Checks
if all fields are filled and no user is currently being edited (editId == null).
● const newUser = {...};: Creates an object representing the new user.
● fetch("https://676a3a7a863eaa5ac0ddb69d.mockapi.io/users",
{...}): Sends a POST request to the mock API to create the new user.
○ method: "POST": Specifies that the request is to create new data.
○ body: JSON.stringify(newUser): Converts the newUser object to
JSON format and sends it as the request body.
● .then(() => {...}): Once the request is successful:
○ this.fetchUsers();: Re-fetches the updated list of users.
○ this.setState({...});: Resets the form fields to empty and sets
editId to null.
● alert("Please Enter All Values in Fields");: If not all fields are filled,
show an alert to the user.
Editing a User:
javascript
Copy code
edit = (user) => {
this.setState({
userName: user.userName,
userFatherName: user.userFatherName,
userMotherName: user.userMotherName,
userEmail: user.userEmail,
userDOB: user.userDOB,
editId: user.id,
});
};
● edit = (user) => {...}: Defines the method for editing an existing user when
the "Edit" button is clicked.
● this.setState({...}): Updates the state with the data of the user being edited
(pre-filling the form fields) and stores the editId of the user to track the user being
edited.
fetch(`https://676a3a7a863eaa5ac0ddb69d.mockapi.io/users/${editId}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(updatedUser),
})
.then((response) => response.json())
.then(() => {
this.fetchUsers();
this.setState({
userName: "",
userFatherName: "",
userMotherName: "",
userEmail: "",
userDOB: "",
editId: null,
});
});
}
};
Deleting a User:
javascript
Copy code
delete = (id) => {
fetch(`https://676a3a7a863eaa5ac0ddb69d.mockapi.io/users/${id}`, {
method: "DELETE",
})
.then(() => {
this.fetchUsers();
});
};
● delete = (id) => {...}: Defines the method for deleting a user when the
"Delete" button is clicked.
● fetch(..., { method: "DELETE" }): Sends a DELETE request to the API to
remove the user with the given id.
● .then(() => {...}): After the user is deleted, it calls this.fetchUsers(); to
reload the list of users.
return (
<div className="container">
{/* Registration Form */}
<div className="form-container">
<h2 className="form-heading">Registration Form</h2>
<input
type="text"
name="userName"
placeholder="Your Name"
value={userName}
onChange={this.inputChange}
className="form-field-input"
/>
<br />
<input
type="text"
name="userFatherName"
placeholder="Father Name"
value={userFatherName}
onChange={this.inputChange}
className="form-field-input"
/>
<br />
<input
type="text"
name="userMotherName"
placeholder="Mother Name"
value={userMotherName}
onChange={this.inputChange}
className="form-field-input"
/>
<br />
<input
type="email"
name="userEmail"
placeholder="Your Email"
value={userEmail}
onChange={this.inputChange}
className="form-field-input"
/>
<br />
<input
type="date"
name="userDOB"
value={userDOB}
onChange={this.inputChange}
className="form-field-input"
/>
<br />
{this.state.editId ? (
<button type="submit" onClick={this.handleUpdateUser}
className="form-field-input btn bg-primary">
Update User
</button>
) : (
<button type="submit" onClick={this.handleAddUser}
className="form-field-input btn bg-success">
Add User
</button>
)}
</div>
● render() {...}: The render method returns the JSX layout to be displayed. It
contains:
○ A registration form where users can input their details.
○ Buttons to either "Add User" or "Update User" depending on whether editId
is set.
○ A table that displays the list of users fetched from the API, with "Edit" and
"Delete" buttons for each user.
That’s the breakdown of the code! It’s a simple CRUD app that uses React to manage user
data and interact with an API.