Discussion on implementing "withDocument" during migration to v3 and fixing issues with using Sanity client outside React.

7 replies
Last updated: Jun 22, 2023
Hi team, I am currently migrating to v3.
How to implement the "withDocument" ?

import { withDocument } from 'part:@sanity/form-builder';
AI Update

In Sanity Studio v3, withDocument from part:@sanity/form-builder has been replaced by the useFormValue hook. The parts system was completely removed in v3, so you'll need to refactor your custom input components to use hooks instead.

Here's how to migrate:

Old v2 pattern:

import { withDocument } from 'part:@sanity/form-builder';

const MyCustomInput = withDocument(({ document, type, value, onChange }) => {
  // Access document here
  console.log(document)
  return <input ... />
})

New v3 pattern:

import { useFormValue } from 'sanity'

const MyCustomInput = (props) => {
  // Get the entire document with an empty array
  const document = useFormValue([])
  
  // Or get specific fields
  const title = useFormValue(['title'])
  const authorId = useFormValue(['author', '_ref'])
  
  return <input ... />
}

Key differences:

  • Getting the entire document: Use useFormValue([]) with an empty array to get the complete document object, equivalent to what withDocument provided
  • Accessing specific fields: Pass a path array like ['fieldName'] for top-level fields or ['parent', 'child'] for nested fields
  • No HOC wrapper: v3 uses hooks directly inside your component instead of higher-order components
  • Reactive: The hook automatically re-renders your component when the accessed values change

The useFormValue hook only works within the form builder context (inside custom input components). If you need document data in other contexts like document actions, you'll need to use different approaches like the useDocumentOperation hook or fetch data via the Sanity client.

Hey Mark, here's the update for
withDocument
per the Migration Cheat Sheet .
Thanks! I got it right. ❤️
Hi
user B
, how about the client?Use case is custom function like slugify
I have created a hook for react component.
I am referring to using sanity client outside React.
I already fixed it. Thanks!
Great! Nice work, Mark!

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.

Was this answer helpful?