How to update a field programmatically when saving a document in Sanity?
Hey! Great question. For automatically updating a field like readingTime when a blog post is saved, you have a couple of approaches:
Best Option: Sanity Functions
The modern, recommended way to handle this is with Sanity Functions. These are serverless functions that run on Sanity's infrastructure and can be triggered by document events like publishing or updating.
Here's why Functions are great for your use case:
- No external infrastructure needed
- Automatically triggered when documents change
- Can calculate reading time based on content and update the field programmatically
- Works across all your datasets
You'd set up a function that triggers on document publish/update, calculates the reading time from your text content, and patches the document with the new readingTime value. Check out the Functions quickstart guide to get started - you can initialize it with the Sanity CLI (v4.5.0+) and deploy it directly.
One important note: Functions don't currently prevent recursive loops, so you'll want to be careful that your function doesn't trigger itself when it updates the readingTime field. You can handle this by checking if the field actually needs updating before patching.
Alternative: Custom Input Component
If you want the calculation to happen client-side in the Studio, you could create a custom input component that calculates reading time whenever the text field changes and updates the hidden field. However, this approach means the calculation only happens when someone is actively editing in the Studio, not when documents are created/updated via API.
For your use case with a hidden field that should auto-update on save, Sanity Functions are definitely the way to go - they'll ensure the reading time is always calculated consistently regardless of how the document is updated.
Show original thread6 replies
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.