I want to get the detail property per id from clicking the property list, I have got the property
value but can't retrieve the category
values using the foreign key.
This is my test.jsx
component:
import React, { useState, useEffect } from 'react';
import { axiosInstance } from '../config/config.js';
function PropertyList() {
const [properties, setProperties] = useState([]);
const fetchPro = async () => {
await axiosInstance.get('/propertys').then((res) => {
// console.log(res.data.result);
const datas = res.data.result;
setProperties(datas);
console.log(datas);
});
};
useEffect(() => {
fetchPro();
}, []);
return (
<div>
<h1>Property List</h1>
<ul>
{properties.map((property) => (
<div className="bg-danger">
<li key={property.id}>
<a href={`/propertydetaillist/${property.id}`}>{property.name}</a>
</li>
</div>
))}
</ul>
</div>
);
}
export default PropertyList;
This is my testdetail.jsx
component:
import React, { useState, useEffect } from 'react';
import { axiosInstance } from '../config/config.js';
import { useParams, withRouter } from 'react-router-dom';
function PropertyDetails(props) {
const [property, setProperty] = useState({});
const { id } = useParams();
const fetchProDetail = async () => {
await axiosInstance.get(`/propertys/detail/${id}`).then((res) => {
// console.log(res.data.result);
const datas = res.data.result;
setProperty(datas);
console.log(datas);
});
};
useEffect(() => {
fetchProDetail();
console.log(property);
}, [id]);
return (
<div>
{property ? (
<div>
<h1>{property.category.id}</h1>
<h1>{property.name}</h1>
<p>{property.description}</p>
<p>Price: {property.propertyImage}</p>
</div>
) : (
<p>Loading...</p>
)}
</div>
);
}
export default PropertyDetails;
This is the problem when I click one of the property list
I want to get the categories value by using foreign key in properties table.
property
is initially an object:
const [property, setProperty] = useState({});
The code only checks that property
exists, but not that property.category
exists prior to accessing an id
property.
<div>
{property ? (
<div>
<h1>{property.category.id}</h1> // error when property.category undefined
<h1>{property.name}</h1>
<p>{property.description}</p>
<p>Price: {property.propertyImage}</p>
</div>
) : (
<p>Loading...</p>
)}
</div>
Just place a null-check on the category
property. Provide a fallback value if you like. {}
is a defined, truthy object, so if you are also wanting to render the loading UI while the property
data is fetched then I suggest also starting with a falsey property
value.
Example:
const [property, setProperty] = useState(null);
...
<div>
{property ? (
<div>
<h1>{property.category?.id ?? "No Category Id"}</h1>
<h1>{property.name}</h1>
<p>{property.description}</p>
<p>Price: {property.propertyImage}</p>
</div>
) : (
<p>Loading...</p>
)}
</div>