0% found this document useful (0 votes)
15 views20 pages

Untitled Document

The document provides a step-by-step guide to integrate a mock API with a React application for performing CRUD operations. It includes instructions for setting up dependencies, understanding CRUD operations, and implementing functions to create, read, update, and delete user data. The final code example demonstrates how to manage user data using state and API calls in a React component.

Uploaded by

kkannake964
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views20 pages

Untitled Document

The document provides a step-by-step guide to integrate a mock API with a React application for performing CRUD operations. It includes instructions for setting up dependencies, understanding CRUD operations, and implementing functions to create, read, update, and delete user data. The final code example demonstrates how to manage user data using state and API calls in a React component.

Uploaded by

kkannake964
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

To integrate the mock API

(https://676a3a7a863eaa5ac0ddb69d.mockapi.io/users) with the React


application for performing CRUD operations (Create, Read, Update, and Delete), you need
to follow these steps:

1. Install Necessary Dependencies

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';

2. Understanding the CRUD Operations with the Mock API

The API URL you're provided with


(https://676a3a7a863eaa5ac0ddb69d.mockapi.io/users) is a mock API hosted
on mockapi.io. It follows the RESTful API design, meaning that you can perform the
following operations:

● GET (Read): Fetch data (e.g., list of users).


● POST (Create): Add new data (e.g., adding a new user).
● PUT (Update): Modify existing data (e.g., updating a user's details).
● DELETE (Delete): Remove data (e.g., deleting a user).

3. Steps to Integrate the API with the React Application

Here is a breakdown of how to integrate each CRUD operation with the mock API:

Step 1: Setup State and Form Inputs

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.

Step 2: Fetch Users (Read Operation)


To display the list of users in your table, you need to fetch the data from the API.

1. componentDidMount() lifecycle method to fetch users when the component loads.


2. Use fetch() to send a GET request to the mock API.

javascript
Copy code
componentDidMount() {
// Fetch users when the component mounts
this.fetchUsers();
}

// Fetch users from the API


fetchUsers = () => {
fetch("https://676a3a7a863eaa5ac0ddb69d.mockapi.io/users")
.then((response) => response.json()) // Parse response as JSON
.then((data) => this.setState({ users: data })); // Update
state with users data
};

Step 3: Add New User (Create Operation)

When the user submits the form to add a new user:

1. Collect the form data (userName, userFatherName, etc.).


2. Send a POST request to the mock API to create a new user.

javascript
Copy code
handleAddUser = () => {
const { userName, userFatherName, userMotherName, userEmail,
userDOB, editId } = this.state;

if (userName && userFatherName && userMotherName && userEmail &&


userDOB && editId == null) {
const newUser = { userName, userFatherName, userMotherName,
userEmail, userDOB };
fetch("https://676a3a7a863eaa5ac0ddb69d.mockapi.io/users", {
method: "POST", // POST request to add a new user
headers: {
"Content-Type": "application/json", // Data will be
sent as JSON
},
body: JSON.stringify(newUser), // Convert user data to
JSON
})
.then((response) => response.json()) // Wait for the
response
.then(() => {
this.fetchUsers(); // Re-fetch the user list after
adding
this.setState({
userName: "",
userFatherName: "",
userMotherName: "",
userEmail: "",
userDOB: "",
editId: null,
});
});
} else {
alert("Please Enter All Values in Fields");
}
};

Step 4: Edit User (Update Operation)

To edit an existing user:

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;

if (userName && userFatherName && userMotherName && userEmail &&


userDOB) {
const updatedUser = { userName, userFatherName,
userMotherName, userEmail, userDOB };

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
});
});
}
};

Step 5: Delete User (Delete Operation)

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
});
};

Final Code with API Integration

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';

export default class CrudApp extends Component {


constructor(props) {
super(props);
this.state = {
users: [],
userName: "",
userFatherName: "",
userMotherName: "",
userEmail: "",
userDOB: "",
editId: null,
};
}

componentDidMount() {
this.fetchUsers();
}

fetchUsers = () => {
fetch("https://676a3a7a863eaa5ac0ddb69d.mockapi.io/users")
.then((response) => response.json())
.then((data) => this.setState({ users: data }));
};

inputChange = (e) => {


const { name, value } = e.target;
this.setState({ [name]: value });
};

handleAddUser = () => {
const { userName, userFatherName, userMotherName, userEmail,
userDOB, editId } = this.state;

if (userName && userFatherName && userMotherName && userEmail &&


userDOB && editId == null) {
const newUser = { userName, userFatherName, userMotherName,
userEmail, userDOB };
fetch("https://676a3a7a863eaa5ac0ddb69d.mockapi.io/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newUser),
})
.then((response) => response.json())
.then(() => {
this.fetchUsers();
this.setState({
userName: "",
userFatherName: "",
userMotherName: "",
userEmail: "",
userDOB: "",
editId: null,
});
});
} else {
alert("Please Enter All Values in Fields");
}
};
edit = (user) => {
this.setState({
userName: user.userName,
userFatherName: user.userFatherName,
userMotherName: user.userMotherName,
userEmail: user.userEmail,
userDOB: user.userDOB,
editId: user.id,
});
};

handleUpdateUser = () => {
const { userName, userFatherName, userMotherName, userEmail,
userDOB, editId } = this.state;

if (userName && userFatherName && userMotherName && userEmail &&


userDOB) {
const updatedUser = { userName, userFatherName,
userMotherName, userEmail, userDOB };

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,
});
});
}
};

delete = (id) => {


fetch(`https://676a3a7a863eaa5ac0ddb69d.mockapi.io/users/${id}`,
{
method: "DELETE",
})
.then(() => {
this.fetchUsers();
});
};

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.

Imports and Initial Setup:


javascript
Copy code
import React, { Component } from 'react';
import './CrudApp.css';
import Table from 'react-bootstrap/Table';

● import React, { Component } from 'react';: Imports React and the


Component class from the React library. This allows us to create a class-based
component.
● import './CrudApp.css';: Imports the custom CSS file to style the component.
● import Table from 'react-bootstrap/Table';: Imports the Table
component from the react-bootstrap library to use Bootstrap styles for displaying
the table.
Constructor and State Initialization:
javascript
Copy code
constructor(props) {
super(props);
this.state = {
users: [],
userName: "",
userFatherName: "",
userMotherName: "",
userEmail: "",
userDOB: "",
editId: null,
};
}

● constructor(props): The constructor is a special method used to initialize state


and bind event handlers in class components.
● super(props): Calls the constructor of the parent Component class to properly
initialize the component.
● this.state = {...}: Initializes the state of the component. The state stores:
○ users: An array to store user data.
○ userName, userFatherName, userMotherName, userEmail, userDOB:
Fields to store form inputs.
○ editId: Holds the ID of the user being edited (null initially, indicating no user
is being edited).

ComponentDidMount - Fetching Users:


javascript
Copy code
componentDidMount() {
this.fetchUsers();
}

● componentDidMount(): A lifecycle method that gets called once the component


has been rendered to the screen. It’s used for fetching data or setting up
subscriptions.
● this.fetchUsers();: Calls the fetchUsers function (defined later) to load the
user data from the mock API after the component has mounted.
Fetching Users:
javascript
Copy code
fetchUsers = () => {
fetch("https://676a3a7a863eaa5ac0ddb69d.mockapi.io/users")
.then((response) => response.json())
.then((data) => this.setState({ users: data }));
};

● 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.

Handling Form Input Changes:


javascript
Copy code
inputChange = (e) => {
const { name, value } = e.target;
this.setState({ [name]: value });
};

● inputChange = (e) => {...}: Defines a method to handle changes in form


input fields.
● const { name, value } = e.target;: Destructures the name and value
from the event target (i.e., the input field that was changed).
● this.setState({ [name]: value });: Dynamically updates the state by
setting the field with the name of the input element to the new value. For example, if
name="userName", it updates this.state.userName.

Adding a New User:


javascript
Copy code
handleAddUser = () => {
const { userName, userFatherName, userMotherName, userEmail,
userDOB, editId } = this.state;

if (userName && userFatherName && userMotherName && userEmail &&


userDOB && editId == null) {
const newUser = { userName, userFatherName, userMotherName,
userEmail, userDOB };
fetch("https://676a3a7a863eaa5ac0ddb69d.mockapi.io/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newUser),
})
.then((response) => response.json())
.then(() => {
this.fetchUsers();
this.setState({
userName: "",
userFatherName: "",
userMotherName: "",
userEmail: "",
userDOB: "",
editId: null,
});
});
} else {
alert("Please Enter All Values in Fields");
}
};

● 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.

Updating an Existing User:


javascript
Copy code
handleUpdateUser = () => {
const { userName, userFatherName, userMotherName, userEmail,
userDOB, editId } = this.state;
if (userName && userFatherName && userMotherName && userEmail &&
userDOB) {
const updatedUser = { userName, userFatherName, userMotherName,
userEmail, userDOB };

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,
});
});
}
};

● handleUpdateUser = () => {...}: Defines the method for updating a user's


details.
● const { ... } = this.state;: Destructures the state to get the form data and
the editId.
● if (userName && ... && userDOB): Ensures that all fields are filled before
proceeding with the update.
● const updatedUser = {...};: Creates a new object representing the updated
user data.
● fetch(..., { method: "PUT", ... }): Sends a PUT request to the API to
update the user with the given editId.
○ method: "PUT": Specifies that the request is to update existing data.
○ body: JSON.stringify(updatedUser): Sends the updated user data
as a JSON string.
● .then(() => {...}): After updating the user:
○ this.fetchUsers();: Re-fetches the user list.
○ this.setState({...});: Resets the form fields and clears the editId.

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.

Rendering the Form and User Table:


javascript
Copy code
render() {
const { users, userName, userFatherName, userMotherName,
userEmail, userDOB } = this.state;

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>

{/* Table displaying users */}


<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-2">Edit</button>
<button onClick={() => this.delete(user.id)}
className="btn bg-danger">Delete</button>
</td>
</tr>
))}
</tbody>
</Table>
</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.

You might also like