#hydratation with api
4 messages · Page 1 of 1 (latest)
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:
-
Create a new
.astrofile in thesrc/pages/q/directory named[query].astro. The square brackets indicate that this is a dynamic route. -
In this file, you'll need to export an async function named
getStaticPaths(). This function should return an array of objects, each containing theparamsfor a specific route. For example:
export async function getStaticPaths() {
return [
{ params: { query: "water" } },
// Add more paths as needed
];
}
- You can then use
Astro.propsto 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 };
- 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.
For more information, you can refer to the Astro Documentation (https://docs.astro.build/en/tutorial/5-astro-api/2/#_top) and the Astro API Reference (https://docs.astro.build/en/reference/api-reference/#getstaticpaths).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@pure cloud kapa.ai is still learning and improving, please let us know how it did by reacting below