Member-only story
Sanity.io — Compute-a-field
Sanity has gained significant momentum in 2020 as a next-gen CMS architecture. One of its main advantages is how seamlessly it works with react components, allowing developers to build custom flows to ease the tedious nature of data entry for CMS managers and provide tactical field validation.
While my experience has been mostly smooth with Sanity, one challenge keeps coming up — I want to autofill a given field based on other attributes of a given document. For example, CMS managers are tasked to make some updates, and then I have to go back and update a field that is based on other documents and fields they have edited. The computed-field sanity plugin may help alleviate some of this pain.
The main use case is when a document may have a value that is expensive or difficult to evaluate, but rarely or never changes. The computed-field plugin essentially memoizes the computed value into an input value on the document.
An Example — Sanity University
To illustrate how this may help us, let’s think of a simple schema where we have a Course
, a ScheduledCourse
and an Instructor
document. Course
documents contain information on the course. ScheduledCourse
documents have a startTime
date value and point to a Course
, and an instructor for each time that course takes place. At the beginning or end of a term, we could compute some values on the Course
document.
In the code below, we use ComputedField
to allow easy calculation of some of the fields