Astro JS - Data Fetching



Data Fetching

Astro provides multiple ways to fetch data from various sources like APIs, databases, and files. You can use the built-in fetch function to fetch data from any source. The fetch function is similar to the browser's fetch API, but it is optimized for Astro's build process.

The fetch() Function

The fetch function is a global function used to fetch data from a URL. The fetch function returns a promise that resolves to the Response to that request, whether it is successful or not. All Astro components have access to the global fetch() function in their component script to make HTTP requests to APIs using the full URL.

This fetch call will be executed at build time, and the data will be available to the component template for generating dynamic HTML. If SSR mode is enabled, any fetch calls will be executed at runtime.

Example

Let's see an example of fetching data from an API using the fetch function.

---
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await response.json();
---

<html>
    <body>
        <h1>Blog Posts</h1>
        {posts.map(post => (
        <article>
            <h2>{post.title}</h2>
            <p>{post.body}</p>
        </article>
        ))}
    </body>
</html>

Output

The output is shown below. You can see that the blog posts are displayed in the browser.

Astro Data Fetching - Fetch Function

Dynamic Data Fetching (SSR)

Sometime, the data in your API provides may change frequently. In such cases, you can use the Astro's server-side rendering (SSR) feature to fetch data dynamically at runtime. By configuring your project for SSR, you can fetch data on each request, ensuring the content is up-to-date. Let's see how to do this.

Enable SSR

First, we need to enable SSR in the Astro project. To do this, open the 'astro.config.mjs' file and set the 'output' property to 'server'.

// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  output: 'server',
});

With SSR enabled, you can fetch data dynamically in your components:

---
const response = await fetch('https://api.example.com/data');
const data = await response.json();
---

<html>
    <body>
        <h1>{data.title}</h1>
        <p>{data.content}</p>
    </body>
</html>

Fetching Data in Framework Components

If you're using framework components (e.g., React, Svelte) within Astro, you can perform data fetching inside these components using their respective lifecycle methods. For instance, in a React component:

Example

Let's see an example of fetching data in a React component using the useEffect hook.

import { useState, useEffect } from 'react';

function DataComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    async function fetchData() {
      const response = await fetch('https://api.example.com/data');
      const result = await response.json();
      setData(result);
    }
    fetchData();
  }, []);

  if (!data) return <div>Loading...</div>;

  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.content}</p>
    </div>
  );
}

export default DataComponent;
Advertisements