I am new to react and I try to get data from the database and display that data in the frontend. This is the code that I wrote to do this task.
const { id } = useParams();
console.log(id);
const [posts, setPosts] = useState({});
useEffect(()=>{
getOnePost();
}, []);
useEffect(()=>{
if (posts && posts.location) {
console.log(posts.location);
console.log(posts.location.longitude);
console.log(posts.location.latitude);
}
}, [posts]);
const getOnePost = async () => {
try {
const response = await axios.get(`/buyerGetOnePost/${id}`)
console.log(response);
const allPost=response.data.onePost;
setPosts(allPost);
} catch (error) {
console.error(`Error: ${error}`)
}
}
console.log(posts);
console.log(posts.location.longitude);
console.log(posts.location.latitude);
I pass an id to API and get relevant data from the backend.
When I call console.log(posts), it prints the data that get from the backend successfully:

Posts data have a location object. When I try to print location data in the console like this, it also gives the output successfully:
useEffect(()=>{
if (posts && posts.location) {
console.log(posts.location);
console.log(posts.location.longitude);
console.log(posts.location.latitude);
}
}, [posts]);
This is the location data:

But when I try to print the location data like this:
console.log(posts.location.longitude);
console.log(posts.location.latitude);
I get:
Type Error: Cannot read property of 'longitude' undefined.
How do I solve this problem?