Content & Data
ใน React คุณดึงข้อมูลด้วย getServerSideProps, getStaticProps หรือ useEffect+fetch ใน Astro ข้อมูลอยู่ใน frontmatter --- (ทำงานตอน build หรือ server) หรือใน content collections (MD/MDX ที่มี type safety) ไม่มีการ fetch ฝั่ง browser โดย default
บทเรียนในโมดูลนี้
หัวข้อที่มีชื่อว่า “บทเรียนในโมดูลนี้”| บทเรียน | สิ่งที่จะได้เรียนรู้ |
|---|---|
| Frontmatter Fetch | await fetch() ใน frontmatter เทียบกับ getServerSideProps |
| Content Collections | defineCollection + zod schema เทียบกับ contentlayer |
| Rendering Markdown | render(entry) เทียบกับ MDX ใน Next |
| Dynamic from Data | getStaticPaths() จาก collection |
การดึงข้อมูล: React vs Astro
หัวข้อที่มีชื่อว่า “การดึงข้อมูล: React vs Astro”// pages/blog.tsx (Next.js)import { useEffect, useState } from 'react';
export default function Blog() { const [posts, setPosts] = useState([]);
useEffect(() => { fetch('https://api.example.com/posts') .then(r => r.json()) .then(setPosts); }, []);
return ( <ul> {posts.map(post => ( <li key={post.id}>{post.title}</li> ))} </ul> );}---// src/pages/blog.astroconst res = await fetch('https://api.example.com/posts');const posts = await res.json();---<ul> {posts.map((post) => ( <li>{post.title}</li> ))}</ul>สังเกต: ใน Astro await fetch() อยู่โดยตรงใน frontmatter ทำงานตอน build time (static) หรือ per-request (SSR) ไม่มี useEffect ไม่มี loading state ไม่มี JavaScript ฝั่ง client ที่ถูกส่งไปสำหรับ fetch
ตัวอย่าง inline data
หัวข้อที่มีชื่อว่า “ตัวอย่าง inline data”---
// In a real project, replace this array with await fetch(...) in the frontmatter
const posts = [
{ id: 1, title: "Getting started with Astro" },
{ id: 2, title: "Content collections deep dive" },
{ id: 3, title: "Islands architecture explained" },
];
---
<html lang="en">
<head><meta charset="utf-8" /><title>Posts</title></head>
<body style="font-family:sans-serif;padding:2rem">
<h1>Blog Posts</h1>
<ul>
{posts.map((post) => (
<li style="margin:0.5rem 0">{post.title}</li>
))}
</ul>
</body>
</html>