👉 [Visit the DatoCMS homepage](https://www.datocms.com) or see [What is DatoCMS?](#what-is-datocms) --- # datocms-listen ![MIT](https://img.shields.io/npm/l/datocms-listen?style=for-the-badge) ![MIT](https://img.shields.io/npm/v/datocms-listen?style=for-the-badge) [![Build Status](https://img.shields.io/travis/datocms/datocms-listen?style=for-the-badge)](https://travis-ci.org/datocms/datocms-listen) A lightweight, TypeScript-ready package that offers utilities to work with DatoCMS [Real-time Updates API](https://www.datocms.com/docs/real-time-updates-api) inside a browser. ## Installation ``` npm install datocms-listen ``` ## Example Import `subscribeToQuery` from `datocms-listen` and use it inside your components like this: ```js import { subscribeToQuery } from "datocms-listen"; const unsubscribe = await subscribeToQuery({ query: ` query BlogPosts($first: IntType!) { allBlogPosts(first: $first) { title nonExistingField } } `, variables: { first: 10 }, token: "YOUR_TOKEN", includeDrafts: true, onUpdate: (update) => { // response is the GraphQL response console.log(update.response.data); }, onStatusChange: (status) => { // status can be "connected", "connecting" or "closed" console.log(status); }, onChannelError: (error) => { // error will be something like: // { // code: "INVALID_QUERY", // message: "The query returned an erroneous response. Please consult the response details to understand the cause.", // response: { // errors: [ // { // fields: ["query", "allBlogPosts", "nonExistingField"], // locations: [{ column: 67, line: 1 }], // message: "Field 'nonExistingField' doesn't exist on type 'BlogPostRecord'", // }, // ], // }, // } console.error(error); }, onError: (error) => { // error is a MessageEvent, the actual error is in error.data console.log(error.data); }, onEvent: (event) => { // event will be // { // status: "connecting|connected|closed", // channelUrl: "...", // message: "MESSAGE", // response: Response // } }, }); ``` ## Initialization options | prop | type | required | description | default | | ------------------ | ------------------------------------------------------------------------------------------ | ------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------ | | query | string \| [`TypedDocumentNode`](https://github.com/dotansimha/graphql-typed-document-node) | :white_check_mark: | The GraphQL query to subscribe | | | token | string | :white_check_mark: | DatoCMS API token to use | | | onUpdate | function | :white_check_mark: | Callback function to receive query update events | | | onChannelError | function | :x: | Callback function to receive channelError events | | | onStatusChange | function | :x: | Callback function to receive status change events | | | onError | function | :x: | Callback function to receive error events | | | onEvent | function | :x: | Callback function to receive other events | | | variables | Object | :x: | GraphQL variables for the query | | | includeDrafts | boolean | :x: | If true, draft records will be returned | | | excludeInvalid | boolean | :x: | If true, invalid records will be filtered out | | | environment | string | :x: | The name of the DatoCMS environment where to perform the query (defaults to primary environment) | | | contentLink | `'vercel-1'` or `undefined` | :x: | If true, embed metadata that enable Content Link | | | baseEditingUrl | string | :x: | The base URL of the DatoCMS project | | | cacheTags | boolean | :x: | If true, receive the Cache Tags associated with the query | | | reconnectionPeriod | number | :x: | In case of network errors, the period (in ms) to wait to reconnect | 1000 | | fetcher | a [fetch-like function](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) | :x: | The fetch function to use to perform the registration query | window.fetch | | eventSourceClass | an [EventSource-like](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) class | :x: | The EventSource class to use to open up the SSE connection | window.EventSource | | baseUrl | string | :x: | The base URL to use to perform the query | `https://graphql-listen.datocms.com` | ## Events ### `onUpdate(update: UpdateData)` This function will be called every time the channel sends an updated query result. The `updateData` argument has the following properties: | prop | type | description | | -------- | ------ | ---------------------------- | | response | Object | The GraphQL updated response | ### `onStatusChange(status: ConnectionStatus)` The `status` argument represents the state of the server-sent events connection. It can be one of the following: - `connecting`: the subscription channel is trying to connect - `connected`: the channel is open, we're receiving live updates - `closed`: the channel has been permanently closed due to a fatal error (i.e. an invalid query) ### `onChannelError(errorData: ChannelErrorData)` The `errorData` argument has the following properties: | prop | type | description | | -------- | ------- | ------------------------------------------------------------------ | | code | string | The code of the error (i.e. `INVALID_QUERY`) | | message | string | A human-friendly message explaining the error | | fatal | boolean | If true, the channel has been closed and will not reconnect | | response | Object | The raw response returned by the endpoint, if available (optional) | ### `onError(error: MessageEvent)` This function is called when connection errors occur (network errors, SSE errors). The `error` argument is a standard [MessageEvent](https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent). The actual error object is available in `error.data`. ### `onEvent(event: EventData)` This function is called when other events occur. The `event` argument has the following properties: | prop | type | description | | ---------- | -------- | ---------------------------------------------- | | status | string | The current connection status (see above) | | channelUrl | string | The current channel URL | | message | string | A human-friendly message explaining the event | | response | Response | The HTTP response from the registration request | ## Return value The function returns a `Promise<() => void>`. You can call the function to gracefully close the SSE channel. --- # What is DatoCMS? DatoCMS - The Headless CMS for the Modern Web [DatoCMS](https://www.datocms.com/) is the REST & GraphQL Headless CMS for the modern web. Trusted by over 25,000 enterprise businesses, agencies, and individuals across the world, DatoCMS users create online content at scale from a central hub and distribute it via API. We ❤️ our [developers](https://www.datocms.com/team/best-cms-for-developers), [content editors](https://www.datocms.com/team/content-creators) and [marketers](https://www.datocms.com/team/cms-digital-marketing)! **Why DatoCMS?** - **API-First Architecture**: Built for both REST and GraphQL, enabling flexible content delivery - **Just Enough Features**: We believe in keeping things simple, and giving you [the right feature-set tools](https://www.datocms.com/features) to get the job done - **Developer Experience**: First-class TypeScript support with powerful developer tools **Getting Started:** - ⚡️ [Create Free Account](https://dashboard.datocms.com/signup) - Get started with DatoCMS in minutes - 🔖 [Documentation](https://www.datocms.com/docs) - Comprehensive guides and API references - ⚙️ [Community Support](https://community.datocms.com/) - Get help from our team and community - 🆕 [Changelog](https://www.datocms.com/product-updates) - Latest features and improvements **Official Libraries:** - [**Content Delivery Client**](https://github.com/datocms/cda-client) - TypeScript GraphQL client for content fetching - [**REST API Clients**](https://github.com/datocms/js-rest-api-clients) - Node.js/Browser clients for content management - [**CLI Tools**](https://github.com/datocms/cli) - Command-line utilities for schema migrations (includes [Contentful](https://github.com/datocms/cli/tree/main/packages/cli-plugin-contentful) and [WordPress](https://github.com/datocms/cli/tree/main/packages/cli-plugin-wordpress) importers) **Official Framework Integrations** Helpers to manage SEO, images, video and Structured Text coming from your DatoCMS projects: - [**React Components**](https://github.com/datocms/react-datocms) - [**Vue Components**](https://github.com/datocms/vue-datocms) - [**Svelte Components**](https://github.com/datocms/datocms-svelte) - [**Astro Components**](https://github.com/datocms/astro-datocms) **Additional Resources:** - [**Plugin Examples**](https://github.com/datocms/plugins) - Example plugins we've made that extend the editor/admin dashboard - [**Starter Projects**](https://www.datocms.com/marketplace/starters) - Example website implementations for popular frameworks - [**All Public Repositories**](https://github.com/orgs/datocms/repositories?q=&type=public&language=&sort=stargazers)