Home > database >  Looping through an array using AlpineJS returns no results
Looping through an array using AlpineJS returns no results

Time:12-31

I'm attempting to loop through an array using AlpineJS, but for the life of me, I can't get any output.

I'm hoping someone that is more familiar with AlpineJS may be able to assist.

Thanks in advance.

And here's the code:

<script>
function alpineInstance() {
  return {
    books: []
  }
}
</script>

<div 
x-data="alpineInstance()"
x-init="fetch('https://www.googleapis.com/books/v1/volumes?q=Alpine')
  .then(response => response.json())
  .then(data => books = data)">
  <template x-for="(book, index) in books" :key="index">
    <div x-text="book.items.volumeInfo.title"></div>
  </template>
</div>

CodePudding user response:

It looks like you've got the wrong idea of what kind of data this API returns. Copy the URL you're passing to the fetch function and paste it into the browser. Hopefully, you'll see pretty quickly that this endpoint doesn't return an array, it returns an object!

function alpineInstance() {
  return {
    // we'll set our data to hold an object
    bookResponse: {}
  }
}
<html>

<head>
  <script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
</head>

<body>
  <div x-data="alpineInstance()" x-init="fetch('https://www.googleapis.com/books/v1/volumes?q=Alpine')
  .then(response => response.json())
  .then(data => bookResponse = data)">
    <!-- instead of mapping over an object, which will throw an error, we'll map over bookResponse.items !-->
    <template x-for="(item, index) in bookResponse.items" :key="index">
    <div x-text="item.volumeInfo.title"></div>
  </template>
  </div>
</body>

</html>

  • Related