Real-time streaming updates of content

    Live updates can be extremely useful both for content editors and the regular visitors of your app/website:

    • Content-editors in Preview 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 (ie. live-news coverage).

    Inside a React project, it's extremely easy to use our Real-time Updates API to perform such changes, as it only involves replacing the useQuery hook with a the useQuerySubscription hook that the react-datocms package makes available:

    import React from "react";
    import { useQuerySubscription } from "react-datocms";
    const App: React.FC = () => {
    const { status, error, data } = useQuerySubscription({
    query: `
    query AppQuery($first: IntType) {
    allBlogPosts {
    slug
    title
    }
    }`,
    variables: { first: 10 },
    token: "YOUR_API_TOKEN",
    });
    const statusMessage = {
    connecting: "Connecting to DatoCMS...",
    connected: "Connected to DatoCMS, receiving live updates!",
    closed: "Connection closed",
    };
    return (
    <div>
    <p>Connection status: {statusMessage[status]}</p>
    {error && (
    <div>
    <h1>Error: {error.code}</h1>
    <div>{error.message}</div>
    {error.response && (
    <pre>{JSON.stringify(error.response, null, 2)}</pre>
    )}
    </div>
    )}
    {data && (
    <ul>
    {data.allBlogPosts.map((blogPost) => (
    <li key={blogPost.slug}>{blogPost.title}</li>
    ))}
    </ul>
    )}
    </div>
    );
    };
    export default App;