#How to send fetch data to page partial?
3 messages · Page 1 of 1 (latest)
Hi @winged vector. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Astro, you can fetch data in the frontmatter of your Astro component using the fetch() function. This data can then be used in your component or passed to other components as props. Here's a basic example:
---
const response = await fetch('<https://randomuser.me/api/'>);
const data = await response.json();
const randomUser = data.results[0];
---
<h1>User</h1>
<h2>{randomUser.name.first} {randomUser.name.last}</h2>
In this example, we're fetching data from an API and then using it in our component. If you want to pass this data to another component, you can do so like this:
---
import Contact from '../components/Contact.jsx';
import Location from '../components/Location.astro';
const response = await fetch('<https://randomuser.me/api/'>);
const data = await response.json();
const randomUser = data.results[0];
---
<h1>User</h1>
<h2>{randomUser.name.first} {randomUser.name.last}</h2>
<Contact client:load email={randomUser.email} />
<Location city={randomUser.location.city} />
In this example, we're passing the fetched data as props to the Contact and Location components.
Remember, all data in Astro components is fetched when a component is rendered. Your deployed Astro site will fetch data once, at build time. In dev, you will see data fetches on component refreshes. If you need to re-fetch data multiple times client-side, use a framework component or a client-side script in an Astro component.