How to update a hidden field programmatically when updating a document in Sanity.io.

6 replies
Last updated: Mar 6, 2023
Afternoon, does anyone know if there’s some way I can update some data programmatically when updating a document? e.g I’d like to update a
readingTime
hidden field when a user saves a blog post based on the text content in said blog post. Cheers!
Mar 3, 2023, 2:52 AM
Mar 3, 2023, 5:55 AM
Thanks, User. Unfortunately this doesn't seem to be able to be used with GraphQL. I was hoping for some kind of
onAfterUpdate
callback in the schema or something.
Mar 3, 2023, 6:44 AM
Hum. I guess you could create a webhook to write a patch to the dataset whenever the relevant document is published?
However, this seems quite roundabout to me, since if you want to compute the readingTime for a field you could do it
directly in GROQ .
You could additionally have a field in the editor in case you want to override it as well.
Mar 3, 2023, 6:49 AM
Yeah, that's a bit convoluted for the use-case.
Mar 3, 2023, 6:51 AM
You could use a custom input component or a document action. For a custom input, you could use
renderDefault
so that you don’t actually have to reimplement the component or logic of the field, but use something like a
useEffect
to write to your hidden field. It would likely write on every keystroke and may impact performance within the Studio. If you use a document action, you can replace the default Publish action so that it updates the field, then completes the action .
Mar 3, 2023, 8:57 PM
Ah, document action would possibly be a goer. Would be good if actions could be run against the normal publish action.
Mar 6, 2023, 8:05 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?