1

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>

1 Answer 1

4

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much Brendan! You're absolutely right in your response and I'm very grateful for your help. Thank you.

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.