#hydratation with api

4 messages · Page 1 of 1 (latest)

cedar forgeBOT
#

Hi @pure cloud. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To create a static page and then hydrate it with an API, you can use Astro's getStaticPaths() function. This function allows you to specify which page routes to build and pass each page its own props.

Here's a step-by-step guide on how you can achieve this:

  1. Create a new .astro file in the src/pages/q/ directory named [query].astro. The square brackets indicate that this is a dynamic route.

  2. In this file, you'll need to export an async function named getStaticPaths(). This function should return an array of objects, each containing the params for a specific route. For example:

export async function getStaticPaths() {
  return [
    { params: { query: "water" } },
    // Add more paths as needed
  ];
}
  1. You can then use Astro.props to access the data passed to each page. For example, if you're fetching data from an API, you might do something like this:
const { query } = Astro.params;
const data = await fetch(`<https://api.example.com/q/${query}`>);
const props = await data.json();

return { props };
  1. In your Astro component, you can then use this data to hydrate your page. For example:
---
const { query } = Astro.params;
const { data } = Astro.props;
---
<html>
  <body>
    <h1>{query}</h1>
    <p>{data}</p>
  </body>
</html>

Remember, Astro components are HTML-only templating components with no client-side runtime. However, you can use a <script> tag in your Astro component template to send JavaScript to the browser that executes in the global scope. This can be useful for hydrating your page with dynamic data from an API.

#

@pure cloud kapa.ai is still learning and improving, please let us know how it did by reacting below