Skip to content

Instantly share code, notes, and snippets.

@marcelozarate
Created July 21, 2022 10:58
Show Gist options
  • Save marcelozarate/7630723d2adea307ecb83e24bb5312ed to your computer and use it in GitHub Desktop.
Save marcelozarate/7630723d2adea307ecb83e24bb5312ed to your computer and use it in GitHub Desktop.
Alpine.JS first time use (consuming API)
<!DOCTYPE html>
<html lang="en" data-theme="coffee">
<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">
<link
href="https://cdn.jsdelivr.net/npm/daisyui@2.6.0/dist/full.css"
rel="stylesheet"
type="text/css"
/>
<script src="https://cdn.tailwindcss.com"></script>
<title>Alpine First Use</title>
</head>
<body>
<script src="//unpkg.com/alpinejs" defer></script>
<div x-data="{ users: [], editingUser: 0, originalName: ''}"
x-init="fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(data => users = data)">
<template x-for="user in users">
<div class="p-3">
<span x-text="user.name" class="text-lg text-primary"></span>
(<span x-text="user.username" class="p-1"></span> - <span x-text="user.email" class="p-1"></span>)
<button x-on:click="editingUser = user.id; originalName = user.name" class="btn btn-sm">Edit Records</button>
<div x-show="user.id === editingUser">
<input type="text" x-model="user.name" class="input input-bordered w-full max-w-xs">
<div class="btn-group m-2">
<button x-on:click="fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'PATCH',
body: JSON.stringify({
name: 'TEST',
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((json) => console.log(json));" class="btn btn-success btn-sm">Save</button><button x-on:click="editingUser = null; user.name = originalName;" class="btn btn-error btn-sm">Cancel</button>
</div>
</div>
<button x-on:click="fetch('https://jsonplaceholder.typicode.com/users/'+user.id, {
method: 'DELETE',
});" class="btn btn-error btn-sm m-2">
Delete
</button>
</div>
</template>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment