Sanity: [form-builder] An officially supported way to get at the document content

Created on 8 Dec 2017  路  2Comments  路  Source: sanity-io/sanity

In order to get at the content of the entire document from an input component, this is what I have to do today:

import React from 'react'
import PropTypes from 'prop-types'

export default class DestinationViewer extends React.Component {
  static contextTypes = {
    formBuilder: PropTypes.any,
  }

  constructor(props, context) {
    super()
    const {formBuilder} = context
    console.log(context)
    this.state = {document: formBuilder.getDocument()}
    this.unsubscribe = formBuilder.onPatch(({snapshot}) => {
      // we will also receive "delete"-patches, with {snapshot: null}. Don't pass null documents.
      if (snapshot) {
        this.setState({document: snapshot})
      }
    })
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  render() {
    console.log(this.state)
    const {sendAt, sentAt} = this.props.value || {}
    return (
      <div>
        <pre>{JSON.stringify(this.state, null, 2)}</pre>
      </div>
    )
  }
}

It is undocumented and not very easy to explain. We need an official, obvious, forward compatible way to do this.

Enhancement

Most helpful comment

We have a (undocumented) withDocument higher order component for this.

Example:

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

export default withDocument(class MyInput extends React.Component {
  render() {
    const {document} = this.props
    return <pre>{JSON.stringify(document)}</pre>
  }
})

All 2 comments

We have a (undocumented) withDocument higher order component for this.

Example:

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

export default withDocument(class MyInput extends React.Component {
  render() {
    const {document} = this.props
    return <pre>{JSON.stringify(document)}</pre>
  }
})

@bjoerge some of the properties only come with _ref and _type. Is there a way to get them as the whole object?

Was this page helpful?
0 / 5 - 0 ratings