i’ve been trying to make an update page for a web app page that has values from a database.
i go to the update page from the student page where i have 20 different students listed , let’s say that i chose student 3, the page link is supposed to be something like localhost:3000/update/3 but it returns as localhost:3000/update/undefined. When i try updating the update button doesn’t send me back to the student page (or any page at all) so basically i’m stuck at the update page.
Here are my codes for some of the pages (also i’m using a Navbar as well at which at first made me think maybe that’s the issue but i don’t think it’s relevant to the case so it’s not included.)
Studetn.js (http://localhost:3000/Studetn)
import React, { useEffect , useState} from 'react'
import axios from 'axios'
import { Link } from 'react-router-dom'
function Studetn() {
const [student, setStudent] = useState([])
useEffect(()=>{
axios.get('http://localhost:8081/')
.then(res => setStudent(res.data))
.catch(err => console.log(err));
}, [])
// Function to format the date
const formatDate = (dateString) => {
// Assuming dateString is now in the 'YYYY-MM-DD' format
return new Date(dateString).toLocaleDateString('en-GB', {
year: 'numeric',
month: 'short',
day: '2-digit',
timeZone: 'UTC'
});
};
return (
<div className='d-flex v-100 bg-primary justify-content-center '>
<div className='w-50 bg-white rounded p-3'>
<Link to="/create" className='btn btn-success'>Add +</Link>
<table className='table'>
<thead>
<tr>
<th>Student ID</th>
<th>Name</th>
<th>Surname</th>
<th>Department</th>
<th>Date of Birth</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{
student.map((data,i)=> (
<tr key={i}>
<td>{data.student_id}</td>
<td>{data.first_name}</td>
<td>{data.last_name}</td>
<td>{data.department}</td>
<td>{formatDate(data.date_of_birth)}</td>
<td>
{console.log("Generated Link:", `/Studetn/update/${data.ID}`)}
<Link to={`/update/${data.ID}`} className='btn btn-primary'>Update</Link>
<button className='btn btn-danger ms-2'>Delete</button>
</td>
</tr>
))
}
</tbody>
</table>
</div>
</div>
)
}
export default Studetn
server.js (my backend)
const express = require("express");
const cors = require("cors");
const mysql = require("mysql");
const app = express();
app.use(express.json())
app.use(cors());
const db = mysql.createConnection({
host:"localhost",
user: "root",
password: "AGad-dags4",
database: "students"
})
app.get("/", (req, res) => {
const sql = "SELECT student_id, first_name, last_name, DATE_FORMAT(date_of_birth, '%Y-%m-%d') AS formatted_date, department FROM student";
db.query(sql, (err, data) => {
if (err) return res.json(err);
// Process data and send response with formatted dates
const formattedData = data.map(student => ({
...student,
date_of_birth: student.formatted_date, // Replace date_of_birth with the formatted date
}));
return res.json(formattedData);
});
});
app.get("/concessionscholarship", (req, res) => {
const sql = "SELECT * FROM concessionscholarship";
db.query(sql,(err, data) => {
if(err) return res.json(err);
return res.json(data);
})
})
app.get("/fee", (req, res) => {
const sql = "SELECT * FROM fee";
db.query(sql,(err, data) => {
if(err) return res.json(err);
return res.json(data);
})
})
app.get("/marks", (req, res) => {
const sql = "SELECT * FROM marks";
db.query(sql,(err, data) => {
if(err) return res.json(err);
return res.json(data);
})
})
app.get("/stream", (req, res) => {
const sql = "SELECT * FROM stream";
db.query(sql,(err, data) => {
if(err) return res.json(err);
return res.json(data);
})
})
app.post('/create', (req,res)=>{
const sql = "INSERT INTO student(first_name,last_name,date_of_birth,department) VALUES (?)";
const values = [
req.body.first_name,
req.body.last_name,
req.body.date_of_birth,
req.body.department
];
db.query(sql,[values], (err,data)=> {
if(err) return res.json("Error");
return res.json(data);
})
})
app.put('/Studetn/update/:id', (req,res)=>{
const sql = "update student set first_name = ?, last_name = ?, date_of_birth = ?, department = ? where ID = ?";
const values = [
req.body.first_name,
req.body.last_name,
req.body.date_of_birth,
req.body.department
];
const id = req.params.id;
db.query(sql,[...values, id], (err,data)=> {
if(err) return res.json("Error");
return res.json(data);
})
})
app.listen(8081, () => {
console.log("listening");
})
App.js (my routes)
import React from "react";
import 'bootstrap/dist/css/bootstrap.min.css'
import{BrowserRouter, Routes, Route} from 'react-router-dom'
import Student from './pages/Studetn';
import Scholarship from "./pages/concessionscholarship";
import Fee from "./pages/fee";
import Marks from "./pages/marks";
import Stream from "./pages/stream";
import Navbar from "./components/Navbar";
import Home from "./pages/";
import CreateStudent from "./pages/CreateStudent";
import UpdateStudent from "./pages/UpdateStudent";
function App() {
return (
<div className="App">
<BrowserRouter>
<Navbar />
<Routes>
<Route exact path='/' element={<Home />}></Route>
<Route path="/Studetn" element={<Student />} />
<Route path="/create" element={<CreateStudent />} />
<Route path="/update/:id" element={<UpdateStudent />} />
<Route path="/concessionscholarship" element={<Scholarship />} />
<Route path="/fee" element={<Fee />} />
<Route path="/marks" element={<Marks />} />
<Route path="/stream" element={<Stream />} />
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
UpdateStudent.js (my “update” page that is supposed to be working)
import axios from 'axios';
import React, { useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom';
function UpdateStudent() {
const [first_name,setfirst_name]= useState('')
const [last_name,setlast_name]= useState('')
const [date_of_birth,setdate_of_birth]= useState('')
const [department,setdepartment]= useState('')
const{id} = useParams();
const navigate = useNavigate();
function handleSubmit(event){
event.preventDefault();
axios.put(`http://localhost:8081/update/${id}`, {first_name,last_name,date_of_birth,department})
.then(res=>{
console.log(res);
navigate('/');
}).catch(err=> console.log(err));
}
return (
<div className='d-flex vh-100 bg-primary justify-content-center align-items-center'>
<div className='w-50 bg-white rounded p-3'>
<form onSubmit={handleSubmit}>
<h2>Update Student</h2>
<div className='mb-2'>
<label htmlFor="">Name</label>
<input type="text" placeholder='Enter Name' className='form-control'
onChange={e=> setfirst_name(e.target.value)} ></input>
</div>
<div className='mb-2'>
<label htmlFor="">Surname</label>
<input type="text" placeholder='Enter Surname' className='form-control'
onChange={e=> setlast_name(e.target.value)} ></input>
</div>
<div className='mb-2'>
<label htmlFor="">Date of Birth</label>
<input type="date" placeholder='Enter DoB' className='form-control'
onChange={e=> setdate_of_birth(e.target.value)} ></input>
</div>
<div className='mb-2'>
<label htmlFor="">Department</label>
<input type="text" placeholder='Enter Department' className='form-control'
onChange={e=> setdepartment(e.target.value)} ></input>
</div>
<button className='btn btn-success'>Update</button>
</form>
</div>
</div>
)
}
export default UpdateStudent
i just want to update the data on my Student page which in return will update the value in my database.
i have tried changing, checking :id to :ID trying to send id to the console and seeing if it is displayed there correctly or trying to press update button while on network page to see if the ip is pulled and vice versa maybe i did something wrong? i don’t know.