2

So I created this backend json response.

{
    "places": [
        {
            "location": {
                "lat": 40.3714624,
                "lng": 21.7614661
            },
            "_id": "5f9bb2ff4fc07350c317500c",
            "title": "Alcazar Park",
            "description": "A lovely park.",
            "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Empire_State_Building_%28aerial_view%29.jpg/400px-Empire_State_Building_%28aerial_view%29.jpg",
            "creator": "5f9bb2ee4fc07350c317500b",
            "__v": 0,
            "id": "5f9bb2ff4fc07350c317500c"
        },
        {
            "location": {
                "lat": 40.3714624,
                "lng": 21.7614661
            },
            "_id": "5f9bb4f9d92cd5541f5922fc",
            "title": "Alcazar Park",
            "description": "A beautiful park.",
            "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Empire_State_Building_%28aerial_view%29.jpg/400px-Empire_State_Building_%28aerial_view%29.jpg",
            "creator": "5f9bb2ee4fc07350c317500b",
            "__v": 0,
            "id": "5f9bb4f9d92cd5541f5922fc"
        },
        {
            "location": {
                "lat": 40.3714624,
                "lng": 21.7614661
            },
            "_id": "5f9bb632d92cd5541f5922fd",
            "title": "Train station of Larisa",
            "description": "An old but cool train station",
            "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Empire_State_Building_%28aerial_view%29.jpg/400px-Empire_State_Building_%28aerial_view%29.jpg",
            "creator": "5f9bb2ee4fc07350c317500b",
            "__v": 0,
            "id": "5f9bb632d92cd5541f5922fd"
        }
    ]
}

Now I want to display in a list just the title of each place in the array. Here is my code for that in React

const DataFetching = () => {
    const [posts, setPosts] = useState([]);

    useEffect(() => {
        axios
        .get('http://localhost:5000/api/places/user/5f9bb2ee4fc07350c317500b')
        .then(res => {
            console.log(res)
            setPosts(res.data);
        })
        .catch((err) => {
            console.log(err)
        })
    }, []);

    return(
        <div>
            <ul>
                {
                    posts.map(post => <li key={post.id}>{post.title}</li>)
                }
            </ul>
        </div>
    )
}

export default DataFetching;

However, I am getting this error

How can I fix it?

TypeError: posts.map is not a function

Thanks, Theo

3
  • setPosts(res.data.places) Commented Oct 31, 2020 at 13:48
  • Check if res.data is an array or not, error message suggests that its not. Commented Oct 31, 2020 at 13:48
  • return <></> if posts is not an array. Maybe no data is being fetched from the API and posts is undefined Commented Oct 31, 2020 at 13:55

1 Answer 1

3

Try this:

setPosts(res.data.places)


posts?.map(post => <li key={post.id}>{post.title} 

or:

setPosts(res.data)


posts.places?.map(post => <li key={post.id}>{post.title} 
Sign up to request clarification or add additional context in comments.

4 Comments

Optional-chaining will not prevent the error because OP is incorrectly setting the state to an object instead of an array. Optional-chaining will only help if posts is undefined.
What's about this: setPosts(res.data.places)?
Yes that is the correct way to update the state in this case. You don't need optional-chaining here because initial value of places is an empty array. Would be nice if you add an explanation of what OP did wrong and why your answer will work.
True think the better way is: setPosts(res.data) adn use it in render: posts.places?.map(post => <li key={post.id}>{post.title}

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.