Introduction
In the previous article, we learned the fundamentals of React.js including:
Components
JSX
Props
State
Event handling
Now it is time to connect the frontend with the backend and build a complete full-stack application.
This is one of the most exciting parts of the PERN stack because:
React frontend will communicate with Express APIs
Backend will fetch data from PostgreSQL
Data will appear dynamically on the webpage
In this article, we will learn:
How frontend and backend communicate
Using fetch()
Using Axios
React Hooks
Fetching API data
Displaying database records
Handling forms
Creating frontend CRUD operations
Understanding Full-Stack Communication
In the PERN stack:
React Frontend
↓
HTTP Request
↓
Express Backend
↓
PostgreSQL Database
Process Flow
User clicks button in React
React sends request to backend
Express receives request
PostgreSQL processes data
Backend sends response
React updates UI
What is an API Request?
When frontend communicates with backend, it sends:
GET requests
POST requests
PUT requests
DELETE requests
These are called API requests.
Example Backend API
Suppose backend route is:
app.get('/students', async (req, res) => {
const students = await pool.query(
'SELECT * FROM students'
);
res.json(students.rows);
});
This API returns student data in JSON format.
What is JSON?
JSON stands for:
JavaScript Object Notation
It is used for data exchange between frontend and backend.
Example:
[
{
"student_id": 1,
"name": "Rahul",
"course": "BCA",
"age": 20
}
]
Fetching Data Using fetch()
JavaScript provides:
fetch()
to communicate with APIs.
Basic Fetch Example
fetch('http://localhost:5000/students')
.then(response => response.json())
.then(data => console.log(data));
Understanding the Code
| Part | Purpose |
|---|---|
| fetch() | Sends request |
| response.json() | Converts JSON |
| data | API response |
Using useEffect Hook
React provides:
useEffect()
for running code when component loads.
Why useEffect is Important
Without useEffect(), API calls may run repeatedly.
It helps:
Load data once
Improve performance
Avoid unnecessary API calls
Example of useEffect
import { useEffect } from 'react';
useEffect(() => {
console.log('Component Loaded');
}, []);
Understanding Empty Dependency Array
[]
means:
Run only once
When component loads
Fetching API Data in React
Now let’s fetch student data properly.
Complete Example
import { useState, useEffect } from 'react';
function App() {
const [students, setStudents] = useState([]);
useEffect(() => {
getStudents();
}, []);
const getStudents = async () => {
const response = await fetch(
'http://localhost:5000/students'
);
const data = await response.json();
setStudents(data);
};
return (
<div>
<h1>Student List</h1>
{students.map(student => (
<div key={student.student_id}>
<h3>{student.name}</h3>
<p>{student.course}</p>
</div>
))}
</div>
);
}
export default App;
Understanding map()
students.map()
loops through array data and displays elements dynamically.
Why key is Required
React requires:
key
to identify unique elements efficiently.
Example:
key={student.student_id}
What is Axios?
is a popular library used for API requests.
Many developers prefer Axios because:
Simpler syntax
Better error handling
Faster development
Installing Axios
Run:
npm install axios
Axios GET Request Example
import axios from 'axios';
const response = await axios.get(
'http://localhost:5000/students'
);
console.log(response.data);
fetch() vs Axios
| fetch() | Axios |
|---|---|
| Built into browser | External package |
| More code | Cleaner syntax |
| Manual JSON conversion | Automatic conversion |
Creating a Form in React
Now let’s create a form to insert student data.
Example Form
import { useState } from 'react';
function AddStudent() {
const [name, setName] = useState('');
return (
<div>
<input
type="text"
placeholder="Enter Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
);
}
export default AddStudent;
Controlled Components
React forms are called:
Controlled Components
because React controls form values using state.
Handling Form Submission
const handleSubmit = async (e) => {
e.preventDefault();
console.log('Form Submitted');
};
Why preventDefault() is Used
e.preventDefault()
prevents page refresh during form submission.
Sending POST Request
const body = { name, course, age };
await fetch(
'http://localhost:5000/students',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
}
);
Understanding JSON.stringify()
JSON.stringify()
converts JavaScript object into JSON string.
Updating Data in React
PUT request example:
await fetch(
`http://localhost:5000/students/${id}`,
{
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(updatedStudent)
}
);
Deleting Data in React
DELETE request example:
await fetch(
`http://localhost:5000/students/${id}`,
{
method: 'DELETE'
}
);
Full CRUD Flow
| Operation | Frontend Action |
|---|---|
| Create | Form submission |
| Read | Fetch data |
| Update | Edit form |
| Delete | Delete button |
Handling Errors in React
Always use:
try...catch
Example:
try {
const response = await fetch(url);
} catch (err) {
console.error(err.message);
}
CORS Error in React
Sometimes frontend cannot connect to backend.
This happens because of:
CORS Policy
Fixing CORS Error
Install CORS package in backend:
npm install cors
Inside backend:
const cors = require('cors');
app.use(cors());
Real-World Use Cases
React frontend + Express backend is used in:
Student portals
Online test systems
E-commerce platforms
Banking dashboards
SaaS applications
Best Practices
Keep API URLs Separate
Use:
.env
files for API URLs.
Create Reusable Components
Separate:
Forms
Tables
Buttons
Cards
Validate Forms Properly
Check:
Empty inputs
Invalid email
Password length
Use Loading States
Show loading message while fetching data.
Example:
Loading...
Common Beginner Mistakes
Forgetting await
Wrong:
const response = fetch(url);
Correct:
const response = await fetch(url);
Not Converting JSON
Wrong:
const data = response;
Correct:
const data = await response.json();
Infinite API Calls
Wrong:
useEffect(() => {
getStudents();
});
Correct:
useEffect(() => {
getStudents();
}, []);
Conclusion
You have now learned how to connect React frontend with Express backend in the PERN stack.
You learned:
API requests
fetch()
Axios
useEffect()
Form handling
CRUD operations
Error handling
Dynamic UI rendering
Now your application is becoming a real full-stack web application.
Comments
Post a Comment