Learn Fate

Compose views around components

Chapter 2 of 6

Split the tracker into a panel and a count label. The panel requests progress. The label owns the selection it needs and receives a reference to the record.

import { useRequest, useView, view, type ViewRef } from 'react-fate';
import type { Progress } from './state';

const PageCountView = view<Progress>()({ pages: true });
const ProgressPanelView = view<Progress>()({ ...PageCountView });

function PageCount({ progress }: { progress: ViewRef<'Progress'> }) {
  const { pages } = useView(PageCountView, progress);
  return <span>{pages} pages read</span>;
}

export function ProgressSummary() {
  const { progress } = useRequest({
    progress: { view: ProgressPanelView },
  });

  return <PageCount progress={progress} />;
}

This is the division of work:

  • view<Progress>()(...) declares the fields a component can read.
  • useRequest(...) resolves the root selection and gives you a reference to the record.
  • useView(view, ref) reads the selected fields and subscribes to changes for that record.

Think of a view as a reusable selection, like a GraphQL fragment. Every record reference carries the views linked to it. Composing PageCountView into the parent selection links it to the reference the parent passes down.

Try it

Add ProgressSummary beside the two buttons. Confirm that every click updates the summary. Then remove pages: true from PageCountView and inspect the error where pages is read. Restore the field. This is data masking: even when another component has already fetched a field, your component has to declare it.

Next, remove the spread from ProgressPanelView and restore it after observing what happens. The spread matters because the child must read a view linked to its reference.

Views and data masking