I got this error when I am trying to get house details from database.
houseinfo.js
import React, { useState, useEffect } from 'react';
const HouseInfo = ({ match }) => {
const [listings, setListings] = useState(null);
const id = match.params.id; // Get house ID from URL
useEffect(() => {
// Fetch house data from API based on house ID
const fetchListings = async () => {
try {
const response = await fetch(`http://localhost:80/api/houseinfo/${id}`);
const data = await response.json();
setListings(data);
} catch (error) {
console.error('Error fetching house:', error);
}
};
fetchListings();
}, [id]);
if (!listings) {
return <div>Loading...</div>;
}
return (
<div>
<h1>House Information</h1>
<ul>
<li>Title: {listings.title}</li>
<li>Location: {listings.location}</li>
<li>Price: {listings.price}</li>
</ul>
</div>
);
};
export default HouseInfo;
This is my app.js
<Route path="/houseinfo/:id" element={<HouseInfo />} />
I am expecting to get the data from the database and list it in the page but I get that error. I am fairly new to react so I don't know what the error is, I was follwoing an youtube tutorial but it is now working
Assuming you use React-router
you can use the hook useParams()
from the same package, this will return an object containing your url parameters.
It would look like this in your code:
import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router'
const HouseInfo = ({ match }) => {
const [listings, setListings] = useState(null);
const {id} = useParams(); // destructure the returned object to get only the "id" value
useEffect(() => {
//rest of your effect here
...
};
export default HouseInfo;