Ben Rodgers
Ben Rodgers

Reputation: 1

Trying to access element in JSON using Google Books API using React

i'm trying to make a small app to track books i've read and i'm using Google Books API. I've got the call right but when accessing the JSON data i can't seem to select the right element? (i.e. title, author etc.) I would have thought that the kind, totalitems and items elements are the top 3 with items being an array. When called with 'books.items' it shows up empty and when the array call is populated books.items[0] is shows a type error:

"Cannot read property '0' of undefined

I've tried messing about with some random combinations but nothing seems to be working

I'm 'adapting' this guide from pusher.com (this is just a small project) the link to that is: https://pusher.com/tutorials/consume-restful-api-react

my app.js

import React, {Component} from 'react';
import Books from './components/books';

const apikey = 'my key here'
const isbn = '9780395647417'
const url = 'https://www.googleapis.com/books/v1/volumes?q=isbn:' + isbn + '?projection=lite&key=' + apikey;
class App extends Component {
    render() {
        return (
            <Books books={this.state.books} />
        )
    }

    state = {
        books: []
    };

    componentDidMount() {
        fetch(url)
            .then(res => res.json())
            .then((data) => {
                this.setState({ books: data })
            })
            .catch(console.log)
    }
}

export default App;

my books component

import React from 'react'

const Books = ({books}) => {
    return (
        <div>
         {books.items[]}
        </div>
    )
};

export default Books

the object returned

{
"kind": "books#volumes",
"totalItems": 1,
"items": [
{
"kind": "books#volume",
"id": "jlytxgEACAAJ",
"etag": "Kq99jRrSq+c",
"selfLink": "https://www.googleapis.com/books/v1/volumes/jlytxgEACAAJ",
"volumeInfo": {
"title": "The Lord of the Rings",
"authors": [
"John Ronald Reuel Tolkien"
],
"publishedDate": "1994",
"description": "The Fellowship was scattered. Some were bracing hopelessly for war against the ancient evil of Sauron.",
"industryIdentifiers": [],
"readingModes": {},
"printType": "BOOK",
"categories": [],
"averageRating": 5,
"ratingsCount": 1,
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "preview-1.0.0",
"panelizationSummary": {},
"language": "en",
"previewLink": "http://books.google.co.uk/books?id=jlytxgEACAAJ&dq=isbn:9780395647417&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.co.uk/books?id=jlytxgEACAAJ&dq=isbn:9780395647417&hl=&source=gbs_api",
"canonicalVolumeLink": "https://books.google.com/books/about/The_Lord_of_the_Rings.html?hl=&id=jlytxgEACAAJ"
},
"saleInfo": {},
"accessInfo": {},
"searchInfo": {}
}
]
}

Upvotes: 0

Views: 1072

Answers (2)

Bembo
Bembo

Reputation: 1939

books.items.map((item,index) =>(
 <div key={index}>
   <h1>{item.title}</h1>
   
 </div>
))

Upvotes: 0

Maximiliano Poggio
Maximiliano Poggio

Reputation: 1182

Two things:

One, super weird to see the render method in the first part of the component. Always put render as a last method in your component (use hooks and functional components if possible and void render method)

Second,

what is that sintax books.items[]? if you want to render each item of the "books" object, you should do this in Books component:

<div>
{books.items.map(item => <div key={item.id}>{item.title}</div>)
</div>

You will have one div per item showing the title (you can show the property you need...)

Upvotes: 1

Related Questions