Estoy intentando recorrer una matriz usando AlpineJS, pero por mi vida, no puedo obtener ningún resultado.
Espero que alguien que esté más familiarizado con AlpineJS pueda ayudar.
Gracias por adelantado.
Y aquí está el código:
<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>Parece que tiene una idea equivocada de qué tipo de datos devuelve esta API. Copie la URL que está pasando a la función de fetch y péguela en el navegador. Con suerte, verá bastante rápido que este punto final no devuelve una matriz, ¡devuelve un objeto!
function alpineInstance() { return { // we'll set our data to hold an object bookResponse: {} } } <html> <head> <script defer src="https://unpkg.com/alpinejs@3.xx/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>