I have JSON data like this :
{
"kind": "books#volumes",
"totalItems": 3436,
"items": [
{
"kind": "books#volume",
"id": "yMtVngEACAAJ",
"etag": "lo1fkwDSvPU",
"selfLink": "https://www.googleapis.com/books/v1/volumes/yMtVngEACAAJ",
"volumeInfo": {
"title": "We Are in a Book! (An Elephant and Piggie Book)",
"publisher": "Hyperion",
"publishedDate": "2010-09-14",
...
I get it from a google’s API with this function :
const getBookData = async function() {
const response = await fetch("https://www.googleapis.com/books/v1/volumes?q=a&key=AIzaSyBB6WfqDdlr307S_gGh7laVq5UrIpedl_TA")
if (response.status == 200) {
let data = await response.json();
return data;
} else {
new Error(response.statusText)
}
}
export { getBookData }
Finally I try to display the id of the first element of the items array :
<template>
<div class="Book_Carrousel">
<h2>{{ name }}</h2>
<h2>{{ bookData.items[0].id }}</h2>
</div>
</template>
<script>
import Book_Card from './Book_Card.vue'
import { getBookData } from '../api/getBook.js'
export default {
name: 'Book_Carrousel',
props: {
name: {type: String, required: true}
},
components: {
Book_Card
},
data() {
return {
bookData: []
}
},
methods: {
async retrieveBookData() {
this.bookData = await getBookData()
}
},
beforeMount(){
this.retrieveBookData()
}
}
</script>
I have this error :
Uncaught TypeError: $data.bookData.items is undefined
The problem doesn’t come from the link between the api, my function, and the file that uses this function. When I display only the items array everything works :
<h2>{{ bookData.items }}</h2>
But whenever I add brackets after items the error shows up
I also tried to return the items array directly with getBookData. In this case, brackets ( bookData[0] ) work but if I add ‘.id’ ( bookData[0].id )I get the same error as previously mentionned.
Thanks
Edit :
Full JSON below
{
"kind": "books#volumes",
"totalItems": 3436,
"items": [
{
"kind": "books#volume",
"id": "yMtVngEACAAJ",
"etag": "lo1fkwDSvPU",
"selfLink": "https://www.googleapis.com/books/v1/volumes/yMtVngEACAAJ",
"volumeInfo": {
"title": "We Are in a Book! (An Elephant and Piggie Book)",
"publisher": "Hyperion",
"publishedDate": "2010-09-14",
"description": "When Gerald the elephant and Piggie realize that they are in a book, they decide to have some fun with the reader.",
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "1423133080"
},
{
"type": "ISBN_13",
"identifier": "9781423133087"
}
],
"readingModes": {
"text": false,
"image": false
},
"pageCount": 64,
"printType": "BOOK",
"categories": [
"Juvenile Fiction"
],
"averageRating": 5,
"ratingsCount": 3,
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "preview-1.0.0",
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=yMtVngEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=yMtVngEACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.com/books?id=yMtVngEACAAJ&dq=a&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.com/books?id=yMtVngEACAAJ&dq=a&hl=&source=gbs_api",
"canonicalVolumeLink": "https://books.google.com/books/about/We_Are_in_a_Book_An_Elephant_and_Piggie.html?hl=&id=yMtVngEACAAJ"
},
"saleInfo": {
"country": "US",
"saleability": "NOT_FOR_SALE",
"isEbook": false
},
"accessInfo": {
"country": "US",
"viewability": "NO_PAGES",
"embeddable": false,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": false
},
"pdf": {
"isAvailable": false
},
"webReaderLink": "http://play.google.com/books/reader?id=yMtVngEACAAJ&hl=&source=gbs_api",
"accessViewStatus": "NONE",
"quoteSharingAllowed": false
},
"searchInfo": {
"textSnippet": "When Gerald the elephant and Piggie realize that they are in a book, they decide to have some fun with the reader."
}
},
{
"kind": "books#volume",
"id": "9b3jAAAAQBAJ",
"etag": "oF9/I7Tycks",
"selfLink": "https://www.googleapis.com/books/v1/volumes/9b3jAAAAQBAJ",
"volumeInfo": {
"title": "Think Like A Champion",
"authors": [
"Dr. Rudi Webster"
],
"publisher": "Harper Collins",
"publishedDate": "2013-04-10",
"description": "The book contains the secrets of success, and it applies as much to most forms of life's endeavour as it does to sport When you understand that pressure is part and parcel of your life and that there are things you can do to control Wit, you will face up to it in a positive way and use it to your advantage.' -Rahul Dravid Rudi Webster, a doctor who has done pioneering work in the field of sports psychology, draws up a fail-safe recipe for on-the-ground performance optimization in this remarkable book. He ropes in some of the world's finest sportsmen to explain their own success techniques: Mahendra Singh Dhoni, Rahul Dravid, V.V.S. Laxman, Clive Lloyd, Dennis Lillee, Wasim Akram, Jacques Kallis and Sir Garry Sobers. They talk about the four interconnected pillars that performance in sport is built on: fitness, technique, strategy and mental skill - but, unanimously, they declare that the mental pillar is the most important. At the highest level of sport, it is this skill that determines how well the other components are combined and executed. Dr Webster's book aims to optimize every aspect of a player's form and performance. Through inventive techniques, especially visualization and mental rehearsal, he reinforces the practice of a physical skill so that it is learned more quickly and imprinted more powerfully in the mind - and thus better executed. Says ace cricketer V.V.S. Laxman, 'These two techniques help a player improve dramatically. Every young player should [...] make them an important part of their practice and preparation routine.' This book is all you need to call forth your best performance at the right time.",
"industryIdentifiers": [
{
"type": "ISBN_13",
"identifier": "9789350296660"
},
{
"type": "ISBN_10",
"identifier": "9350296667"
}
],
"readingModes": {
"text": true,
"image": false
},
"pageCount": 392,
"printType": "BOOK",
"categories": [
"Sports & Recreation"
],
"maturityRating": "NOT_MATURE",
"allowAnonLogging": false,
"contentVersion": "0.3.3.0.preview.2",
"panelizationSummary": {
"containsEpubBubbles": false,
"containsImageBubbles": false
},
"imageLinks": {
"smallThumbnail": "http://books.google.com/books/content?id=9b3jAAAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.com/books/content?id=9b3jAAAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.com/books?id=9b3jAAAAQBAJ&pg=PT12&dq=a&hl=&cd=2&source=gbs_api",
"infoLink": "https://play.google.com/store/books/details?id=9b3jAAAAQBAJ&source=gbs_api",
"canonicalVolumeLink": "https://play.google.com/store/books/details?id=9b3jAAAAQBAJ"
},
"saleInfo": {
"country": "US",
"saleability": "FOR_SALE",
"isEbook": true,
"listPrice": {
"amount": 19.99,
"currencyCode": "USD"
},
"retailPrice": {
"amount": 19.99,
"currencyCode": "USD"
},
"buyLink": "https://play.google.com/store/books/details?id=9b3jAAAAQBAJ&rdid=book-9b3jAAAAQBAJ&rdot=1&source=gbs_api",
"offers": [
{
"finskyOfferType": 1,
"listPrice": {
"amountInMicros": 19990000,
"currencyCode": "USD"
},
"retailPrice": {
"amountInMicros": 19990000,
"currencyCode": "USD"
},
"giftable": true
}
]
},
"accessInfo": {
"country": "US",
"viewability": "PARTIAL",
"embeddable": true,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": true,
"acsTokenLink": "http://books.google.com/books/download/Think_Like_A_Champion-sample-epub.acsm?id=9b3jAAAAQBAJ&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"pdf": {
"isAvailable": false
},
"webReaderLink": "http://play.google.com/books/reader?id=9b3jAAAAQBAJ&hl=&source=gbs_api",
"accessViewStatus": "SAMPLE",
"quoteSharingAllowed": false
},
"searchInfo": {
"textSnippet": "Batting with <b>a</b> runner because of <b>a</b> bad back, Laxman and number ten batsman Ishant Sharma put on eightyone runs to take the score to 205 before Sharma fell. Laxman who scored seventythree not out, and last man Pragyan Ojha knocked off ..."
}
}
]
}
>Solution :
Vue is accessing bookData.items
before it is loaded, when bookData
is still just an empty array. So bookData.items
is undefined, and bookData.items[0]
will give you the error.
One way to resolve this is to use v-if
:
<h2 v-if="bookData.items">{{ bookData.items[0].id }}</h2>
You might want to show a loading spinner or progress bar during load.
Or you could initialize bookData
with empty items:
data() {
return {
bookData: {items: []}
}
},