0% found this document useful (0 votes)
28 views11 pages

Project Setup

Uploaded by

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

Project Setup

Uploaded by

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

Project Setup

1. Install Node.js:
 Ensure Node.js is installed on your machine.
2. Create Vite Project:
Run the following command to create a new Vite project:
bash
Copy code
npm create vite@latest

3. Follow Tailwind CSS Setup:
 Follow the Tailwind CSS installation guide for Vite:
 Tailwind CSS Guide
4. DaisyUI Installation:
 Go to the ESM tab for installation instructions:
 DaisyUI Installation
5. Choose Theme:
 Set the theme to "night":
 DaisyUI Themes
6. Create Project Structure:
 Create a /src/components folder for your React components.
Component Structure
1. Navbar
 Create Navbar Component:
 Path: /src/components/Navbar.jsx
 Reference for Navbar design:
 DaisyUI Navbar
 Features:
 Implement a search input.
 Add a button:
 DaisyUI Button
2. Table List
 Table Component:
 Reference for Table design:
 DaisyUI Table
 Add Status Button:
 Include a status button for each entry:
 DaisyUI Button
3. Modal
 Modal Component:
 Reference for Modal design:
 DaisyUI Modal
 State Management:
 Create state variables:
 isOpen: Manages modal visibility.
 mode: Determines if the modal is in "add" or "edit" mode.
 Handlers:
 handleOpen: Sets isOpen to true and sets mode based on the button clicked
(either "add" or "edit").
 handleSubmit: Contains logic for adding or editing, and then
sets isOpen to false.
 Components:
 Navbar: Contains the "Add" button that triggers the modal in "add" mode.
 Table: Contains "Edit" buttons for each row, triggering the modal in "edit"
mode.
 Modal: Receives props to manage its state and mode.
4. Select Component
 Select Component:
 Path: /src/components/Select.jsx
 Implement useState and an onChange event for handling values.
Backend Setup
Create Backend Directory:
bash
Copy code
mkdir crud-backend
cd crud-backend
1.
2. Create index.js File:
 Create the main entry file for your backend:
 Path: index.js
3. Initialize Node Project:
 Run the following command to initialize a Node.js project:
bash
Copy code
npm init -y
3. Install Core Dependencies
Express (for HTTP server)
bash
Copy code
npm install express

Dotenv (for environment variable management)
bash
Copy code
npm install dotenv

 Nodemon (for automatic server restarts in development)
bash
Copy code
npm install --save-dev nodemonGet input name , email , job, rate status
 https://daisyui.com/components/input/
 Get dropdown select

https://daisyui.com/
1. Set Up the Backend with Node.js
Initialize a Node.js Project
In your backend folder, initialize a new Node.js project:
bash
Copy code
npm init -y
1.
Add ES Module Support
In package.json, add "type": "module" to allow import statements instead of require:
json
Copy code
{
"name": "backend",
"version": "1.0.0",
"main": "index.js",
"type": "module",
...
}
2.
Install Required Packages
Install Express for creating routes and cors to handle cross-origin requests:
bash
Copy code
npm install express cors
3.
Set Up the Basic Server
In the backend folder, create an index.js file:
javascript
Copy code
// backend/index.js
import express from 'express';
import cors from 'cors';
import clientRoutes from './routes/clients.js'; // Import client routes
const app = express();
app.use(cors()); // Enable CORS
app.use(express.json()); // Middleware to parse JSON
// Set up routes
app.use('/api/clients', clientRoutes);
const PORT = 5000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
4.
2. Create the "Hello Clients" Route
1. Create a Folder for Routes
Inside the backend folder, create a routes folder and add a file
named clients.js.
Define the Route
In clients.js, define a simple GET route that responds with a "Hello Clients" message:
javascript
Copy code
// backend/routes/clients.js
import express from 'express';
const router = express.Router();
router.get('/', (req, res) => {
res.json({ message: 'Hello, Clients!' });
});
export default router;
2. This file defines an API route at /api/clients which responds with a JSON object
containing message: "Hello, Clients!".
3. Test the API Route on the Frontend with React
Install Axios
Navigate to the frontend folder and install Axios for making HTTP requests:
bash
Copy code
npm install axios
1.
Create a Component to Call the API
In your React app, create a component named HelloClients.js inside
the frontend/src/components folder:
javascript
Copy code
// frontend/src/components/HelloClients.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const HelloClients = () => {
const [message, setMessage] = useState('');
useEffect(() => {
const fetchMessage = async () => {
try {
const response = await axios.get('http://localhost:5000/api/clients');
setMessage(response.data.message);
} catch (error) {
console.error('Error fetching message:', error);
}
};
fetchMessage();
}, []);
return (
<div>
<h1>{message || 'Loading...'}</h1>
</div>
);
};
export default HelloClients;
2.
Use the Component in App.js
Import and display the HelloClients component in App.js:
javascript
Copy code
// frontend/src/App.js
import React from 'react';
import HelloClients from './components/HelloClients';
function App() {
return (
<div className="App">
<HelloClients />
</div>
);
}
export default App;
3.
4. Run Both Servers
Start the Node.js Backend
In the backend folder, start the server:
bash
Copy code
node index.js
1.
2. Start the React Frontend
In the frontend folder, start the React development server:
bash
Copy code
npm start
Step 1: Set Up PostgreSQL
1. Download PgAdmin
 Download and install PgAdmin, a popular management tool for PostgreSQL.
2. Create a New Database
 In PgAdmin, create a new database named client_db.
3. Create the clients Table
 Execute the following SQL command to create the clients table:
sql
Copy code
CREATE TABLE clients_tb (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
job VARCHAR(50),
rate NUMERIC(10, 2) DEFAULT 100.00,
isActive BOOLEAN DEFAULT TRUE
);
4.
5. Insert Sample Data
 Populate the clients table with sample data using the following SQL
command:
sql
Copy code
INSERT INTO clients_tb (name, email, job, rate, isActive) VALUES
('Alice Johnson', '[email protected]', 'Software Engineer', 120.00, TRUE),
('Bob Smith', '[email protected]', 'Product Manager', 150.00, TRUE),
('Charlie Davis', '[email protected]', 'Designer', 90.00, TRUE),
('Dana Lee', '[email protected]', 'Data Analyst', 110.00, FALSE),
('Eve Martin', '[email protected]', 'HR Specialist', 100.00, TRUE);
6.
7. View All Rows in PgAdmin
 Check the inserted data in the clients table using PgAdmin.
Step 2: Set Up Node.js Project
1. Install Required Packages
 Run the following command to install the required packages:
bash
Copy code
npm install pg dotenv
2.
3. Create .env File
 In the root folder of your project, create a .env file to store database
connection information.
4. Project Structure
 Create the following folder and file structure:
bash
Copy code
/src
├── /controllers
│ └── userController.js
├── /routes
│ └── userRoutes.js
├── /services
│ └── userService.js
├── db.js
└── index.js
.env
package.json
5.
6. Move index.js and db.js to the /src Folder
 Ensure that both files are located in the src directory.

Step 3: Implement Database Connection


1. Set Up Database Connection in db.js
 In db.js, import pg and dotenv, and set up the database client:
javascript
Copy code
const { Pool } = require('pg');
require('dotenv').config();
const pool = new Pool({
connectionString: process.env.DATABASE_URL, // Define this in your .env file
});
module.exports = {
query: (text, params) => pool.query(text, params),
};
2.
3. Add Error Handling
 Ensure to add error handling for database connections.

Step 4: Create Service and Controller Logic


1. Implement Client Services in userService.js
 Import the query function from db.js and create a function to get all clients:
javascript
Copy code
const db = require('../db');
const getAllClients = async () => {
const res = await db.query('SELECT * FROM clients');
return res.rows;
};
module.exports = {
getAllClients,
};
2.
3. Create Client Controller in userController.js
 Import the services and create an asynchronous function to handle client
retrieval:
javascript
Copy code
const clientService = require('../services/userService');
const getClients = async (req, res) => {
try {
const clients = await clientService.getAllClients();
res.json(clients);
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' });
}
};
module.exports = {
getClients,
};
4.

Step 5: Set Up Routes


1. Define Routes in userRoutes.js
 Create routes for accessing client data:
javascript
Copy code
const express = require('express');
const clientController = require('../controllers/userController');
const router = express.Router();
router.get('/', clientController.getClients); // Route to get all clients
module.exports = router;
2.

Step 6: Set Up the Application


1. Configure the Main Application in index.js
 Import routes and set up the Express application:
javascript
Copy code
const express = require('express');
const userRoutes = require('./routes/userRoutes');
const app = express();
app.use(express.json());
app.use('/api/clients', userRoutes); // API endpoint for clients
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
2.
3. Test the API
 Access the endpoint in your browser or a tool like Postman:
bash
Copy code
http://localhost:3000/api/clients
4.
 You should see the JSON response containing all the clients from the
database:
json
Copy code
[
{"id":1,"name":"Alice
Johnson","email":"[email protected]","job":"Software
Engineer","rate":"120.00","isActive":true},
{"id":2,"name":"Bob Smith","email":"[email protected]","job":"Product
Manager","rate":"150.00","isActive":true},
{"id":3,"name":"Charlie
Davis","email":"[email protected]","job":"Designer","rate":"90.00","isActiv
e":true},
{"id":4,"name":"Dana Lee","email":"[email protected]","job":"Data
Analyst","rate":"110.00","isActive":false},
{"id":5,"name":"Eve Martin","email":"[email protected]","job":"HR
Specialist","rate":"100.00","isActive":true}
5. ]
Steps to Render Data in a React Table
1. Import Required Libraries:
 Import useState and useEffect from React.
 Import axios for making API calls.
2. Setup Component:
 Create a functional component for the table.
3. State Management:
 Use useState to manage the table data and any potential errors.
4. Fetch Data with useEffect:
 Utilize useEffect to fetch data when the component mounts (using an empty
dependency array).
5. Error Handling:
 Implement error catching to handle any issues with the API request.
6. Render Table:
 Map through the fetched data to render rows in a table.
Example Code
Here’s a code snippet illustrating these steps:
jsx
Copy code
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const ClientsTable = () => {
const [clients, setClients] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get('/api/clients');
setClients(response.data);
} catch (err) {
setError(err.message);
}
};
fetchData();
}, []); // Empty dependency array to run only on mount
return (
<div>
{error && <p>Error: {error}</p>}
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
{/* Add more headers as needed */}
</tr>
</thead>
<tbody>
{clients.map(client => (
<tr key={client.id}>
<td>{client.id}</td>
<td>{client.name}</td>
<td>{client.email}</td>
{/* Add more cells as needed */}
</tr>
))}
</tbody>
</table>
</div>
);
};
export default ClientsTable;
1. Download and Open Postman
 Download Postman from the official website.
 Once installed, open Postman from your desktop or by clicking its icon on the
taskbar.
 Right-click the icon and choose “Open Postman” to launch it.
2. Register and Sign In
 Sign up for a Postman account if you don’t have one, or log in if you’re an
existing user.
3. Make an API Request
 Create a new POST request in Postman.
 Enter the URL: http://localhost:3000/api/clients.
In Body > raw > JSON, paste the following JSON data to test
the createClient route:
json
Copy code
{
"name": "John Doe",
"email": "[email protected]",
"job": "Developer",
"rate": 50,
"isactive": true
}

4. Set Up the Server for JSON Parsing
In your main server file (e.g., index.js), add JSON parsing middleware by including
this line:
javascript
Copy code
app.use(express.json());

5. Create createClient Function in clientServices.js
Define an asynchronous query function to insert data into the clients table.
javascript
Copy code
export const createClient = async (clientData) => {
const { name, email, job, rate, isactive } = clientData;
const { rows } = await query(
`INSERT INTO clients (name, email, job, rate, isactive)
VALUES ($1, $2, $3, $4, $5) RETURNING *`,
[name, email, job, rate, isactive]
);
return rows[0];
};

6. Set Up createClient in the Controller
In clientController.js, use req.body to capture the client data and pass it to the
service function:
javascript
Copy code
export const createClient = async (req, res) => {
try {
const clientData = req.body;
const newClient = await clientService.createClient(clientData);
res.status(201).json(newClient);
} catch (error) {
console.error('Error creating client:', error);
res.status(500).json({ message: 'Internal Server Error' });
}
};

7. Testing with Postman
 With the server running, make the POST request
to http://localhost:3000/api/clients in Postman.
 If set up correctly, you should see the newly created client’s data returned in
JSON format.
In modal form .jsx
// Function to handle the form submission
const handleSubmit = async (e) => {
e.preventDefault(); // Prevent default form submission
try {
const clientData = { name, email, job, rate: Number(rate),
isActive: status === 'Active' }; // Prepare the client data
await onSubmit(clientData); // Pass the client data to the parent onSubmit
function
onClose(); // Close the modal
} catch (error) {
console.error("Error adding client:", error); // Log any errors
}
};

In the form
<form onSubmit={handleSubmit}>
// Handle the change of status
const handleStatusChange = (e) => {
setStatus(e.target.value === 'Active'); // Set status as boolean
}
<select value={status ? 'Active' : 'Inactive'} className="select select-bordered w-
full max-w-xs" onChange={handleStatusChange}>
<option value="Inactive">Inactive</option>
<option value="Active">Active</option>
</select>

You might also like