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?

Harshana
  • 25
  • 1
  • 7
  • 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. – tmarwen Aug 02 '21 at 17:48
  • Does this answer your question? [Use Async/Await with Axios in React.js](https://stackoverflow.com/questions/46733354/use-async-await-with-axios-in-react-js) – Janez Kuhar Aug 02 '21 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. – Harshana Aug 02 '21 at 18:18

2 Answers2

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.

MiKr13
  • 1,297
  • 13
  • 20
  • 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. – Harshana Aug 02 '21 at 18:23
  • 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. – MiKr13 Aug 02 '21 at 18:40
  • 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. – Harshana Aug 02 '21 at 18:53
  • 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! – MiKr13 Aug 02 '21 at 19:07
  • 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! – MiKr13 Aug 02 '21 at 19:09
  • I've updated the code to reflect the `post.location` changes in 2nd useEffect – MiKr13 Aug 02 '21 at 19:11
0

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

Sowam
  • 1,674
  • 3
  • 12
  • 30
  • 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. – Harshana Aug 02 '21 at 17:50