Created
August 19, 2022 14:11
-
-
Save cdsaenz/394c1dec9610ae6d1567fb50d2baad62 to your computer and use it in GitHub Desktop.
Demo Alpine JS and Fetch from Remote API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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