This is a React hook to get the latest version of a record from the store, if any.
const record = useFindRecordByKey(key);
useFindRecordByKey()
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>;
}
key
RecordKey
This hook returns a Record
, or undefined
if the record could not be found.
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>
);
}