Skip to content

Client Subscription

The useZenstackRealtime composable gives you the ability to listen for updates from the server and automatically synchronize your store.

When you subscribe to a model, any new CRUD operation affecting that model will be transparently patched into your local cache without requiring a full refetch.

Usage

vue
<!-- app.vue -->
<script setup lang="ts">
const { subscribe, unsubscribe, status } = useZenstackRealtime()

// On Login subscribe
subscribe(['User', 'Post'])
 
// On Logout unsubscribe
unsubscribe(['User', 'Post'])
</script>

<template>
  <div>
    Realtime Status: {{ status }}
  </div>
</template>

TIP

This composable is fully typed. In editors like VS Code, the ['User', 'Post'] array will autocomplete with valid model names strictly based on your schema.zmodel.

API

ts
const { 
  subscribe, 
  unsubscribe, 
  data, 
  error, 
  status, 
  loading 
} = useZenstackRealtime()

Methods

  • subscribe(models: $Zmodel[]): Starts an SSE connection (if not already running) and updates the connection to receive events for the provided model names.
  • unsubscribe(models: $Zmodel[]): Stops listening for events on the specified models. If the subscription list becomes empty, the SSE connection is gracefully aborted.

Reactive State

PropertyTypeDescription
statusRef<'idle' | 'pending' | 'success' | 'error'>Returns the status of the SSE connection.
loadingComputedRef<boolean>true while the connection is opening or trying to reconnect.
dataRef<ClientRealtimeData | null>The raw parsed realtime payload from the server. (Usually you don't need to read this directly, as the store updates automatically.)
errorRef<FetchError | null>Error from the underlying fetch connection (if any).

Under the Hood

When subscribe is called, the composable uses useZenstackSSE dynamically generating a URL like: /api/_zenstack/realtime?subscriptions=User,Post,Reaction

If the connection is lost unexpectedly, useZenstackSSE will attempt to automatically reconnect using a 5-second interval.