React SDK

useRecordByKey

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

const record = useRecordByKey(key);

Call useRecordByKey at the top level of your component to find a record.

function Todo({todoKey}) {
  const todoRecord = useRecordByKey(todoKey);
  return <div>{todoRecord.content.title}</div>;
}

Parameters

  • key RecordKey

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

Returns

This hook returns a Record­

Notes

  • Throws an error if no matching record is found.

  • 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 for some components to only receive the key of the record to display instead of the full record. An example of this might be cases where we need the record to always be up-to-date with its latest version.

Here, we have an app that lets the user select a Todo record and display its details.

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

function TodoList() {
  const [selectedTodoKey, setSelectedTodoKey] = useState();
  return (
    <>
      {/* Display a list of Todos and select on click... */}
      {selectedTodoKey && (
        <TodoDetails todoKey={selectedTodoKey} />
      )}
    </>
  );
}

function TodoDetails({todoKey}) {
  const {content} = useRecordByKey(todoKey);
  return (
    <div>
      <div>Title: {content.title}</div>
      <div>Completed: {content.completed}</div>
    </div>
  );
}
© 2024 Quentez