I am new to react and I try to get data from the backend and display.
const { id } = useParams();
console.log(id);
const [posts, getPosts] = useState([]);
useEffect(()=>{
getOnePost();
}, []);
const getOnePost = async () => {
await axios.get(`/buyerGetOnePost/${id}`)
.then ((response)=>{
const allPost=response.data.onePost;
getPosts(allPost);
})
.catch(error=>console.error(`Error: ${error}`));
}
console.log(posts);
console.log(posts.location.latitude);
console.log(posts.location.longitude);
I passed an id and get data from the backend and it works correctly. But when I try to get the location's latitude and longitude it gives an error like this:
TypeError: Cannot read property 'latitude' of undefined
When I write the code like this :
console.log(posts.location);
console.log(posts.location);
It does not give any error. But when I try to access the data in the location object it gives the above typeError.
This is a screenshot of location object
console.log(posts);
This gives the output of the whole post.
Just like this image. Inside the post, there is an object called location. In the location object, it has an Id, longitude, and latitude. When I console.log(posts.location)
do like this, the location object prints in the console. But when I want to access the longitude and latitude in the location object it gives an error.
How do I solve this issue?