fetch()
is provided by Web API. We can use fetch()
to get data from RESTful API without any packages.
Version
Alpine 3.10
GET
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://unpkg.com/alpinejs" defer></script>
<title>Alpine Lab</title>
</head>
<body x-data="{ posts: [] }" x-init="init($data)">
<ul>
<template x-for="x in posts">
<li x-text="x.title" />
</template>
</ul>
</body>
<script>
let init = async x => {
try {
let res = await fetch('http://localhost:3000/posts')
let data = await res.json()
x.posts = data
} catch (e) {
console.error(e)
}
}
</script>
</html>
Line 17
let init = async x => {
try {
let res = await fetch('http://localhost:3000/posts')
let data = await res.json()
x.posts = data
} catch (e) {
console.error(e)
}
}
fetch()
:usefetch()
to getResponse
from GET actionjson()
:usejson()
to transform fromResponse
toJSON
Conclusion
- Since
fetch()
returns Promise, we have to useasync await
to deal with the data returned byfetch()