1

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:

This shows the posts data

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:

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?

0

1 Answer 1

1

You can use conditional chaining:

posts?.location?.longitude
posts?.location?.latitude

Basically, it won't continue if the term before the ? is falsy. So, it is the same as this:

if(posts && posts.location) doSomething(posts.location.longtitude)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.