0

I need to retrieve names of the books written by a particular author, where author name provided through get request.

My API works fine and retrieves relevant data. In this scenario, I'm getting API response JSON for more than one book.

API response JSON :

[
    {
        "_id": "5cf40d9d74df260aa460a74b",
        "name": "Oliver Twist",
        "author": "Charles Dickens",
        "yearOfPublication": "1839",
        "__v": 0
    },
    {
        "_id": "5cf4115b4b557126a02c6087",
        "name": "David Copperfield ",
        "author": "Charles Dickens",
        "yearOfPublication": "1850",
        "__v": 0
    },
    {
        "_id": "5cf412c54b557126a02c6088",
        "name": "A Christmas Carol ",
        "author": "Charles Dickens",
        "yearOfPublication": "1843",
        "__v": 0
]

I have tried using const books = this.state.data.toString(); and access book names through {books.name}, but it doesn't output the book names. However, when I console.log(), response.data also outputs relevant data successfully as :

0: {_id: "5cf40d9d74df260aa460a74b", name: "Oliver Twist", author: "Charles Dickens", …}
1: {_id: "5cf4115b4b557126a02c6087", name: "David Copperfield ", author: "Charles Dickens", …}
2: {_id: "5cf412c54b557126a02c6088", name: "A Christmas Carol ", author: "Charles Dickens", …}

Can anyone suggest a suitable way to output these values to react front end too ? Thanks in advance.

1
  • 2
    Why .toString() ? just map over this.state.data, i.e this.data.map(books=> console.log(books.name)) Commented Jun 4, 2019 at 2:13

1 Answer 1

1

You don't need the .toString().

Since you have any array you need to specify which element you want or map over the array.

console.log(this.state.data[0].name);

// or to log all names
this.state.data.map(item => console.log(item.name));
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.