DocsGuidesLive Queries

Live Queries

TopGun provides a powerful reactive query system that allows you to subscribe to changes in your data. Unlike traditional databases where you have to poll for updates, TopGun pushes updates to your client in real-time.

Real-time Updates

Changes are pushed to subscribers immediately as they happen, no polling required.

Powerful Filters

Use simple equality matching or complex predicates with logical operators.

React Integration

First-class React hooks for seamless integration with your UI components.

Basic Usage

To create a live query, use the client.query() method. This returns a QueryHandle that you can subscribe to.

src/queries/todos.ts
const query = client.query('todos', {
  where: { completed: false },
  sort: { createdAt: 'desc' }
});

const unsubscribe = query.subscribe((results) => {
  console.log('Active todos:', results);
});

// Later, when you're done:
unsubscribe();

Query Filters

The QueryFilter object supports several options:

  • where: Simple equality matching
  • predicate: Complex conditions using logic operators
  • sort: Sort order
  • limit: Max number of results (coming soon)

Complex Predicates

For more complex filtering, use the predicate field:

src/queries/products.ts
import { Predicates } from '@topgunbuild/client';

const query = client.query('products', {
  predicate: Predicates.and(
    Predicates.greaterThan('price', 100),
    Predicates.equal('category', 'electronics')
  )
});

Available Predicate Methods

MethodDescriptionExample
equal(attr, value)Exact matchPredicates.equal('status', 'active')
notEqual(attr, value)Not equalPredicates.notEqual('type', 'draft')
greaterThan(attr, value)Greater thanPredicates.greaterThan('price', 100)
greaterThanOrEqual(attr, value)Greater or equalPredicates.greaterThanOrEqual('stock', 0)
lessThan(attr, value)Less thanPredicates.lessThan('age', 18)
lessThanOrEqual(attr, value)Less or equalPredicates.lessThanOrEqual('priority', 5)
like(attr, pattern)SQL-like pattern (% = any, _ = single char)Predicates.like('name', '%john%')
regex(attr, pattern)Regular expressionPredicates.regex('email', '^.*@gmail\\.com$')
between(attr, from, to)Range (inclusive)Predicates.between('price', 10, 100)
and(...predicates)Logical ANDPredicates.and(p1, p2, p3)
or(...predicates)Logical ORPredicates.or(p1, p2)
not(predicate)Logical NOTPredicates.not(p1)

React Integration

If you are using React, we recommend using the useQuery hook which handles subscription management automatically.

See the React Hooks reference for detailed documentation on useQuery, useMutation, and other hooks.