Once you've written a specification function, you can retrieve facts matching that specification. When you need those facts in a single snapshot, you will run a query. But when you need to be continuously informed about those facts, then you will start a watch.
The function j.query
returns facts matching a specification as an array.
The first parameter is a starting fact.
The second is a preposition, which you create by calling j.for
with a specification function.
const posts = await j.query(person, j.for(postsByAuthor));
You can extend a preposition using .then
.
This takes another specification function which continues where the previous one left off.
const tags = await j.query(person, j
.for(postsByAuthor)
.then(tagsForPost));
While j.query
is done as soon as it returns the results, you might want to keep watching the results, for example to update a user interface.
Call j.watch
and pass in two functions: the first is called when a fact is added, and the second when a fact is removed.
const postWatch = j.watch(person,
j.for(publishedPostsByAuthor),
addPostToList,
removePostFromList);
function addPostToList(post) {
...
return postListItem;
}
function removePostFromList(postListItem) {
...
}
You can chain watches together to continue loading details within a list.
const titleWatch = postWatch.watch(
j.for(titlesForPost),
setPostTitle);
function setPostTitle(postListItem, postTitle) {
postListItem.text(postTitle.value);
}
When you are done, be sure to call stop
on the top level.
postWatch.stop();
This stops the entire tree of watches so that no further updates are attempted.
If you are using a front-end framework such as React, you will probably use an adapter like Jinaga React rather than creating watches directly.