1

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.

Image 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?

3
  • Would you add the output of the console.log calls? Please do provide text description of the output and object shapes and avoid external asset links. Commented Aug 2, 2021 at 17:48
  • Does this answer your question? Use Async/Await with Axios in React.js Commented Aug 2, 2021 at 17:48
  • @tmarwen as you said I added more details. I do have not 10 reputations yet so I can't add screenshots that's why I add some links. Commented Aug 2, 2021 at 18:18

2 Answers 2

1

There are few problems with your code:

  1. You've defined useState() default value as an empty array [], then you're treating posts as an object.
  2. Secondly by the time the code runs, posts value is [] then you're trying to print out console.log(posts.location.latitude); which will ofcouse give you an error.
  3. Async await usage is not proper.

I would structure my code as something like:

    const { id } = useParams();
    console.log(id);

    const [posts, setPosts] = useState({});
    const [loading, setLoading] = useState(true);

    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}`))
        }
    }

Hope this helps, basically you've added posts as a dependency in 2nd useEffect to run when it's value changes.

Sign up to request clarification or add additional context in comments.

6 Comments

the post have a location object. The latitude and longitude are in that location object as shown in the above screenshots. posts.longitude can not directly access because longitude is in the location object inside the post. That's why I tried posts.location.longitude like this.
Please use this code and then see what is the value inside post.location, if possible, copy & paste it here, then I might be able to help.
I use this code and get the value inside the posts.location. The values are looks like this. {_id: "60f86725c018375a646ecb11", latitude: 7.0811648, longitude: 79.9965184} latitude: 7.0811648 longitude: 79.9965184 _id: "60f86725c018375a646ecb11" [[Prototype]]: Object. If I try posts.location.latitude code I get the latitude data. But if I reload the page then I get above type error.
Hi Harshana, if you're getting this data in posts.location then you can do posts.location.latitude in the 2nd useEffect and it should work. Now coming to error part, how are you rendering the DOM code, can you also attach the return (//whatever code) to the question so that I can help further!
If you can also provide the HTML part of JSX code that would make it easier to pinpoint the problem because at this point your JS code is perfect with this code above!
|
0

It is definitely something wrong with the object. Are you sure that it is posts.location.latitude? What about posts.latitude ?

1 Comment

as I have shown in the above screenshot posts.latitude logs that location object's data in the console. But try to get posts.location.latitude and posts.location.longitude to display the location in a map.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.