Hello, everyone!
I am a beginner and this is my first time making a CRUD app, so this is probably very embarrassing. I am nearly done, but really struggling to get the currently saved data to fill the input fields on my edit page. I have been looking at videos and articles since yesterday, but sadly only getting more confused. I am now getting the data in my console, but having trouble figuring out how to get it on the page. I would really appreciate if someone can point me in the right direction. Let me know if there's any way I can make helping me out easier for you all.
My full edit file:
import axios from 'axios';
import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
const EditHospital = () => {
const navigate = useNavigate();
const location = useLocation();
// Gets the id for the entry being edited from the endpoint
const hospitalId = location.pathname.split('/')[2];
// const [input, setInput] = useState([]);
useEffect(() => {
const getInputs = async () => {
try {
const res = await axios.get(
'http://localhost:4000/hospitals/' + hospitalId
);
// setInput(res.data);
console.log(res.data);
} catch (err) {
console.log(err);
}
};
getInputs();
}, []);
const [input, setInput] = useState({
name: '',
location: '',
type: '',
phone: '',
});
const handleChange = (event) => {
setInput((prev) => ({
...prev,
[event.target.name]: event.target.value,
}));
};
const handleClick = async (event) => {
event.preventDefault();
try {
await axios.put(
'http://localhost:4000/hospitals/' + hospitalId,
input
);
navigate('/');
} catch (err) {
console.log('Unable to process update.');
}
};
return (
<div className='form'>
<h1>Edit Hospital Details</h1>
<input
type='text'
placeholder='name'
onChange={handleChange}
name='name'
/>
<input
type='text'
placeholder='location'
onChange={handleChange}
name='location'
/>
<select
onChange={handleChange}
className='hospital-type-dropdown'
name='type'
>
<option value='general'>General</option>
<option value='pediatric'>Pediatric</option>
<option value='cardiology'>Cardiology</option>
<option value='neurology'>Neurology</option>
<option value='orthopedic'>Orthopedic</option>
</select>
<input
type='text'
placeholder='phone'
onChange={handleChange}
name='phone'
/>
<button className='form-button' onClick={handleClick}>
Save
</button>
</div>
);
};
export default EditHospital;
And, again, I am finally getting the data through when accessing my edit page in my console- but in case it is helpful, here is my get request in the backend:
app.get('/hospitals/:id', (req, res) => {
const hospitalId = req.params.id;
const q = 'SELECT * FROM `hospitals` WHERE id = ?';
db.query(q, [hospitalId], (err, data) => {
if (err) {
return res.json(err);
} else {
return res.json(data);
}
});
});
I apologize for such a long post. I hope someone can point me in the right direction. I would be eternally grateful! Thank you all.