Skip to content

Files

Latest commit

d6701f2 · Jan 11, 2023

History

History
112 lines (85 loc) · 2.44 KB

read.mdx

File metadata and controls

112 lines (85 loc) · 2.44 KB
title
Read Data

There are two ways to retrieve data in Polybase.

  1. Fetch data once with .get()
  2. Listen for real time updates with .onSnapshot()

You can view our example app Polybase Social to see it working in action.

Get a single record

You can read data once, by calling .record(id: string).get() on a collection.

import { Polybase } from "@polybase/client"

const db = new Polybase({ defaultNamespace: "your-namespace" });
const collectionReference = db.collection("cities");

async function getRecord () {
  const { data, block } = await collectionReference.record("id").get();
}

Listen for updates on a record

The .onSnapshot() handler is called on every update for the record after the write is confirmed.

import { Polybase } from "@polybase/client"

const db = new Polybase({ defaultNamespace: "your-namespace" });
const collectionReference = db
  .collection("cities")
  .record("id")
  .onSnapshot(
    (newDoc) => {
      // Handle the change
    },
    (err) => {
      // Optional error handler
    }
  );

List records in a collection

import { Polybase } from "@polybase/client"

const db = new Polybase({ defaultNamespace: "your-namespace" });
const collectionReference = db.collection("cities");

export async function listRecords () {
  const records = await collectionReference.get();
}

Filter records

To use the where() filter, you must have a corresponding index specified on the collection.

import { Polybase } from "@polybase/client"

const db = new Polybase({ defaultNamespace: "your-namespace" });
const collectionReference = db.collection("cities");

export async function listRecordsWithFilter () {
  const records = await collectionReference.where("country", "==", "UK").get();
}

Listen for updates on a collection

import { Polybase } from "@polybase/client"

const db = new Polybase({ defaultNamespace: "your-namespace" });
const collectionReference = db.collection("cities").onSnapshot(
  (newDoc) => {
    // Handle the change
  },
  (err) => {
    // Optional error handler
  }
);

You can also watch for changes on a filtered query.

const db = new Polybase({ defaultNamespace: "your-namespace" });
const collectionReference = db
  .collection("cities")
  .where("country", "==", "UK")
  .onSnapshot(
    (newDoc) => {
      // Handle the change
    },
    (err) => {
      // Optional error handler
    }
  );