Real-time updates
Live updates can be extremely useful both for content editors and the regular visitors of your app/website:
Content-editors in Draft Mode can see drafts directly in the production website, without having to refresh the page;
Visitors can immediately see new content as it gets published, allowing all kinds of real-time interactions with your website/app (e.g., live-news coverage).
The <QueryListener /> component from the @datocms/astro package provides real-time page reload when content changes. It connects to DatoCMS's Real-time Updates API to receive updated query results in real-time, and is able to reconnect in case of network failures.
Simply add the component at the end of your page, passing the same query and variables you used to fetch content:
---import { QueryListener } from '@datocms/astro';import { DATOCMS_CDA_TOKEN } from "astro:env/server";
const query = ` query HomeQuery { blogPost { title } }`;
const data = await executeQuery(query, { includeDrafts: true });---
<article> <h1>{data.blogPost.title}</h1></article>
<QueryListener token={DATOCMS_CDA_TOKEN} includeDrafts query={query}/> Draft Mode + <QueryListener />
Perhaps a more common scenario is activating real-time updates only for content editors in Draft Mode. To avoid repetitive code, you can create a simple wrapper component that checks draft mode status before rendering:
---import { QueryListener } from '@datocms/astro';import { DATOCMS_CDA_TOKEN } from 'astro:env/server';import { isDraftModeEnabled } from '~/lib/draftMode';
const draftModeEnabled = isDraftModeEnabled(Astro.cookies);---
{ draftModeEnabled && ( <QueryListener {...Astro.props} token={DATOCMS_CDA_TOKEN} includeDrafts /> )}Then use it in your pages to enable real-time updates for editors only:
---import { DraftModeQueryListener } from '~/components/DraftModeQueryListener';
const query = `...`;const data = await executeQuery(query, { includeDrafts: draftModeEnabled });---
<article>...</article>
<DraftModeQueryListener query={query} variables={{ slug }} />Reference
Please consult the @datocms/astro documentation to learn more about how to configure <QueryListener />. You can also look at a real-world example in the Astro Starter Kit, which includes a DraftModeQueryListener wrapper component.