Search code examples
astrojs

How do I refresh/rerender an Astro component when data changes?


I have this simple component. How do I refresh/rerender it when I know the API data has changed? Example: When I click one of the dashboard items I will spawn a dialog which contains a form. When that form is submitted the API data will change and I need to refresh the component.

Or do I need VUE, React, or another framework to do this?

---
import Layout from "../layouts/Layout.astro";
import BrokerDashboardItem from "../components/BrokerDashboardItem.astro";

const response = await fetch(
    "https://api/"
);
const data = await response.json();

---

<Layout title="Broker Dashboard">
<div>
    {
        data.map((item) => (
            <BrokerDashboardItem
                priority="{item.priority}"
                date="{item.date}"
                clientName="{item.clientName}"
                statusText="{item.statusText}"
                statusProgress="{item.statusProgress}"
                title="{item.title}"
            />
        ))
    }
</div>
    <style></style>
</Layout>


Solution

  • The Astro component rendering logic is only present on the server, so to re-render on the client you need to choose one of the following

    • Use a framework like Preact, React, Vue, Solid, Svelte etc., which support re-rendering on the client.

    • Write the interactivity describing how to update the component in a <script> tag, for example with a custom element.

    Which you choose is mostly up to personal preference and project requirements. If you have only a few instances of this kind of updating behaviour, I might choose to write a custom element to handle things. But if the project is heavily interactive, often a UI framework will help make that easier to build and maintain.