PythonicRitual
PythonicRitual

Reputation: 9

Mapping API response to JSX

I have a JSON response in the form:

[
    {
        "author": 2,
        "title": "how to draw",
        "slug": "how-to-draw",
        "content": "second attempt",
        "status": 0,
        "date_created": "2020-11-28T20:25:41.650172Z",
        "date_posted": "2020-11-28T20:25:41.650172Z",
        "tags": "none"
    },
    {
        "author": 1,
        "title": "Admin test post",
        "slug": "admin-test-post",
        "content": "This is just a test of the content field!\r\n\r\nParagraph 2",
        "status": 4,
        "date_created": "2020-11-16T21:02:02.521705Z",
        "date_posted": "2020-11-16T21:37:40.477318Z",
        "tags": "a b c"
    }
]

And I am struggling to map the response correctly to a series of divs in ReactJS. The idea would be to have a div for each post, each with the author, title, etc. of the post. I can use post[0].title to take the title of the first element of the array. Am I missing something obvious?

import React, {useState} from 'react';
import axios from 'axios';

const Django = () => {
    const [posts, setPosts] = useState([]);
    // proxy set to http://127.0.0.1:8000/
    const apiLink = "/api/post/";

    const fetchData = async () => {
        const res = await axios.get(`${apiLink}`, { headers: { Accept: "application/json"} });
        console.log(res.data);
        setPosts([res.data]);
    }

    return (
       <div>
          <h1>Posts:</h1>
          <button onClick={fetchData}>Load jokes</button>
          {posts.map((post, key) => {
              //console.log(joke);
              return (
                <div className="data" key={key}>
                    {post.title}
                    {key}
                </div>
            )})}
        </div>
    );
}
export default Django;

Upvotes: 0

Views: 56

Answers (1)

zhulien
zhulien

Reputation: 5715

It is not exactly clear what your problem is, but I suppose you're confused about why you aren't getting any data by directly calling {post.title} in the map body. That's because you're putting the result from your fetch, which is already an array into another array: setPosts([res.data]);. Just change the state setter to setPosts(res.data); and everything in the map should work fine.

Upvotes: 1

Related Questions