ข้ามไปยังเนื้อหา

Content & Data

ใน React คุณดึงข้อมูลด้วย getServerSideProps, getStaticProps หรือ useEffect+fetch ใน Astro ข้อมูลอยู่ใน frontmatter --- (ทำงานตอน build หรือ server) หรือใน content collections (MD/MDX ที่มี type safety) ไม่มีการ fetch ฝั่ง browser โดย default

บทเรียนสิ่งที่จะได้เรียนรู้
Frontmatter Fetchawait fetch() ใน frontmatter เทียบกับ getServerSideProps
Content CollectionsdefineCollection + zod schema เทียบกับ contentlayer
Rendering Markdownrender(entry) เทียบกับ MDX ใน Next
Dynamic from DatagetStaticPaths() จาก collection
React
// 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>
);
}
Astro
---
// src/pages/blog.astro
const 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

Astro
---
// 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>
โค้ดดึงข้อมูลใน Astro component ทำงานที่ไหน?
ฟีเจอร์ใดของ Astro ที่ให้การจัดการเนื้อหา MD/MDX แบบ type-safe?
โดย default Astro ส่ง JS สำหรับดึงข้อมูลไปที่ browser ไหม?