Skip to content

Instantly share code, notes, and snippets.

@cdsaenz
Created August 19, 2022 14:11
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save cdsaenz/394c1dec9610ae6d1567fb50d2baad62 to your computer and use it in GitHub Desktop.
Save cdsaenz/394c1dec9610ae6d1567fb50d2baad62 to your computer and use it in GitHub Desktop.
Demo Alpine JS and Fetch from Remote API
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Alpine Ajax test</title>
</head>
<body>
<h1>Users API Retrieval Test</h1>
<div x-data="createDataRetriever()" x-init="getData()">
USERS LIST
<ul>
<template x-for="user in users" :key="user.id">
<li>
<span class="" x-text="user.phone"></span>
</li>
</template>
</ul>
</div>
<script src="//unpkg.com/alpinejs" defer></script>
<script>
/**
* Alpine instance with data retrieval
*/
function createDataRetriever() {
return {
isLoading: false,
users: [],
getData() {
this.isLoading = true;
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => response.json())
.then((data) => {
this.users = data;
this.isLoading = false;
});
}
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment