Skip to content

Instantly share code, notes, and snippets.

@mcanv
Created December 1, 2020 20:16
Show Gist options
  • Select an option

  • Save mcanv/8ae3bcad6e168b462abac10737eabdf8 to your computer and use it in GitHub Desktop.

Select an option

Save mcanv/8ae3bcad6e168b462abac10737eabdf8 to your computer and use it in GitHub Desktop.
Alpinejs - Get data from api
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AlpineJS - Get data from api</title>
</head>
<body>
<h1>AlpineJS - Get data from api</h1>
<div x-data="app()" x-init="init()">
<template x-for="(post, key) in posts.slice(0,visible)" :key="key">
<div>
<h3 x-text="post.title"></h3>
<p x-text="post.body"></p>
</div>
</template>
<button x-show="posts.length !== 0 && visible < posts.length " @click="visible = visible + 3">Load more</button>
</div>
<script>
function app() {
return {
visible: 3,
posts: [],
apiUrl: 'https://jsonplaceholder.typicode.com',
init() {
fetch(this.apiUrl+'/posts')
.then(response => response.json())
.then(response => {
if(response.length > 0) {
this.posts = response;
} else {
console.log("Couldn't find any post")
}
})
},
}
}
</script>
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js" defer></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment