Let’s begin with Beginners Project 1: Basic CRUD Application. We’ll be using Vite for React setup, Axios for API requests, and JSON Server to simulate a backend. This project will help you understand how to perform basic Create, Read, Update, and Delete (CRUD) operations.
Step 1: Set up the Project
Initialize a new Vite project: Open your terminal and run the following command to create a new Vite project:
npm create vite@latest crud-app --template react
cd crud-app
2. Install required dependencies: We will install axios
for making API requests and json-server
for our mock backend:
npm install axios
npm install json-server
3. Create a db.json
file: In the root of your project, create a db.json
file. This file will serve as our mock database for the JSON server.
Here’s what the db.json
file might look like:
{
"items": [
{ "id": 1, "name": "Item 1", "description": "This is item 1" },
{ "id": 2, "name": "Item 2", "description": "This is item 2" },
{ "id": 3, "name": "Item 3", "description": "This is item 3" }
]
}
4. Run the JSON Server: Run the following command to start the JSON server. It will watch the db.json
file and serve it as an API on http://localhost:5000
.
npx json-server --watch db.json --port 5000
Step 2: Setting Up React Components
Start your React development server: Inside your project directory, start the development server:
npm run dev
2. Edit the src/App.jsx
: We will now set up the basic structure of the app to perform CRUD operations.
Open src/App.jsx
and replace its content with the following:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const App = () => {
const [items, setItems] = useState([]);
const [newItem, setNewItem] = useState({ name: '', description: '' });
const [editItem, setEditItem] = useState(null);
// Fetch all items when the component is mounted
useEffect(() => {
axios.get('http://localhost:5000/items')
.then(response => {
setItems(response.data);
})
.catch(error => {
console.error('Error fetching items:', error);
});
}, []);
// Handle form input changes
const handleChange = (e) => {
const { name, value } = e.target;
setNewItem((prevState) => ({ ...prevState, [name]: value }));
};
// Add a new item
const addItem = () => {
axios.post('http://localhost:5000/items', newItem)
.then(response => {
setItems([...items, response.data]);
setNewItem({ name: '', description: '' });
})
.catch(error => {
console.error('Error adding item:', error);
});
};
// Edit an item
const startEdit = (item) => {
setEditItem(item);
};
// Save edited item
const saveEdit = () => {
axios.put(`http://localhost:5000/items/${editItem.id}`, editItem)
.then(response => {
const updatedItems = items.map(item =>
item.id === editItem.id ? response.data : item
);
setItems(updatedItems);
setEditItem(null);
})
.catch(error => {
console.error('Error updating item:', error);
});
};
// Delete an item
const deleteItem = (id) => {
axios.delete(`http://localhost:5000/items/${id}`)
.then(() => {
setItems(items.filter(item => item.id !== id));
})
.catch(error => {
console.error('Error deleting item:', error);
});
};
return (
<div>
<h1>CRUD Application</h1>
<h2>Items</h2>
<ul>
{items.map((item) => (
<li key={item.id}>
{editItem?.id === item.id ? (
<div>
<input
name="name"
value={editItem.name}
onChange={(e) =>
setEditItem({ ...editItem, name: e.target.value })
}
/>
<input
name="description"
value={editItem.description}
onChange={(e) =>
setEditItem({ ...editItem, description: e.target.value })
}
/>
<button onClick={saveEdit}>Save</button>
<button onClick={() => setEditItem(null)}>Cancel</button>
</div>
) : (
<div>
{item.name} - {item.description}
<button onClick={() => startEdit(item)}>Edit</button>
<button onClick={() => deleteItem(item.id)}>Delete</button>
</div>
)}
</li>
))}
</ul>
<h2>Add New Item</h2>
<input
name="name"
value={newItem.name}
onChange={handleChange}
placeholder="Item Name"
/>
<input
name="description"
value={newItem.description}
onChange={handleChange}
placeholder="Item Description"
/>
<button onClick={addItem}>Add Item</button>
</div>
);
};
export default App;
Step 3: Explanation of the Code
State Management:
items
: stores the list of items fetched from the server.newItem
: stores the data of a new item to be added.editItem
: stores the data of the item being edited.
CRUD Operations:
- Read: On component mount,
useEffect
runs an Axios GET request to fetch the items from the server. - Create: The
addItem
function sends a POST request with the new item data to add it to the server. - Edit: When the edit button is clicked, the item’s data is stored in
editItem
. ThesaveEdit
function sends a PUT request to update the item’s data. - Delete: The
deleteItem
function sends a DELETE request to remove an item from the server.
- Read: On component mount,
Form Handling:
- The
handleChange
function updates the form inputs for adding new items. - The edit section allows for inline editing of items in the list.
- The
Step 4: Running the Project
Start both the JSON Server and the React app:
# In one terminal, start the JSON server:
npx json-server --watch db.json --port 5000
# In another terminal, start the React app:
npm run dev
POSTMAN SETUP
To use Postman with this project, we will create requests for each of the CRUD operations (Create, Read, Update, and Delete). I’ll walk you through creating Postman requests for each type of operation.
Step 1: Set up Postman
Download and Install Postman: If you haven’t already, download and install Postman from here.
Create a New Collection: Open Postman, and create a new collection. You can name it
CRUD App
.
Step 2: Create CRUD Requests in Postman
1. GET: Fetch All Items (READ)
Method:
GET
URL:
http://localhost:5000/items
Description: This request will fetch all items from the JSON server.
Steps:
- Click
+
to create a new request in Postman. - Set the request method to
GET
. - Enter the URL
http://localhost:5000/items
. - Click
Send
. - You should see a list of all items in the response body.
- Click
2. POST: Add a New Item (CREATE)
Method:
POST
URL:
http://localhost:5000/items
Description: This request adds a new item to the JSON server.
Steps:
- Create a new request by clicking
+
. - Set the method to
POST
. - Enter the URL
http://localhost:5000/items
. - Go to the Body tab and select
raw
and then chooseJSON
from the dropdown. - Enter the following JSON in the request body
- Create a new request by clicking
{
"name": "New Item",
"description": "This is a new item"
}
- Click
Send
. - A new item will be added, and you should see the created item in the response body.
- Click
3. PUT: Update an Existing Item (UPDATE)
Method:
PUT
URL:
http://localhost:5000/items/:id
(replace:id
with the actual item ID)Description: This request updates an existing item on the server.
Steps:
- Create a new request and set the method to
PUT
. - Enter the URL
http://localhost:5000/items/1
(assuming you’re updating the item with ID 1). - Go to the Body tab, select
raw
, and chooseJSON
. - Enter the following JSON
- Create a new request and set the method to
{
"name": "Updated Item",
"description": "This item has been updated"
}
- Click
Send
. - You should see the updated item in the response body.
- Click
4. DELETE: Remove an Item (DELETE)
Method:
DELETE
URL:
http://localhost:5000/items/:id
(replace:id
with the actual item ID)Description: This request deletes an item from the JSON server.
Steps:
- Create a new request with the method
DELETE
. - Enter the URL
http://localhost:5000/items/1
(assuming you’re deleting the item with ID 1). - Click
Send
. - If successful, the response should confirm the deletion.
- Create a new request with the method
Step 3: Organize Requests in Postman Collection
Organizing:
- You can organize these requests into a single Postman collection by right-clicking on the collection folder and selecting Add Request.
- Name each request appropriately (e.g.,
GET Items
,POST Add Item
, etc.).
Test Each Request:
- Ensure your JSON server is running (
npx json-server --watch db.json --port 5000
). - Test each of the requests in Postman to confirm they are working correctly.
- Ensure your JSON server is running (
Step 4: Export the Postman Collection (Optional)
Once you have set up all the requests, you can export your Postman collection to share it or keep it for later:
- Click on the three dots next to the collection name.
- Select Export.
- Choose the Collection v2.1 format and save the file.
- You can share this file or re-import it into Postman whenever needed.
Summary of Postman Requests:
- GET: Fetch all items →
http://localhost:5000/items
- POST: Add a new item →
http://localhost:5000/items
- PUT: Update an existing item →
http://localhost:5000/items/:id
- DELETE: Delete an item →
http://localhost:5000/items/:id
Welcome to DevTechTutor.com, your ultimate resource for mastering web development and technology! Whether you're a beginner eager to dive into coding or an experienced developer looking to sharpen your skills, DevTechTutor.com is here to guide you every step of the way. Our mission is to make learning web development accessible, engaging, and effective.