React SDK

useFindRecordByKey

This is a React hook to get the latest version of a record from the store, if any.

const record = useFindRecordByKey(key);

Call useFindRecordByKey at the top level of your component to try to get a record back.

function SelectedTodo({todoKey}) {
  const todoRecord = useFindRecordByKey(todoKey);
  if (!todoRecord) {
    return <Empty />;
  }

  return <div>{todoRecord.content.title}</div>;
}

Parameters

  • key RecordKey

    • Key (entity + id) of the record to get.

Returns

This hook returns a Record­, or undefined if the record could not be found.

Notes

  • Always returns the latest version of the record with this key available in the store. The hook automatically updates when a new version becomes available.

It might be convenient to only store the key of a given record instead of the record itself in order to always display up-to-date data. However, this can result in having a key to a record that was since removed from the store.

Here, we use useFindRecordByKey to avoid passing an expired key to child components.

import {useState} from "react";
import {useFindRecordByKey} from "./baq/store.js";

function Todos() {
  const [selectedKey, setSelectedKey] = useState();
  const selectedRecord = useFindRecordByKey(selectedKey);
  const validSelectedKey = selectedRecord
    ? selectedKey
    : undefined;

  return (
    <>
      {validSelectedKey && (
        <TodoDetails todoKey={validSelectedKey} />
      )}
    </>
  );
}

This hook comes in handy when we expect a record to be removed from the store and want to display a fallback UI when that happens.

function TodoDetails({todoKey}) {
  const todoRecord = useFindRecordByKey(todoKey);
  if (!todoRecord) {
    return <NoTodoSelected />;
  }

  return (
    <div>
      <div>Title:{todoRecord.content.title}</div>
      <div>Completed:{todoRecord.content.completed}</div>
    </div>
  );
}
© 2024 Quentez