Skip to content

Instantly share code, notes, and snippets.

@runeb
Last active June 12, 2023 20:15
Show Gist options
  • Save runeb/caa0d87f043529dc7e035c1142f6219b to your computer and use it in GitHub Desktop.
Save runeb/caa0d87f043529dc7e035c1142f6219b to your computer and use it in GitHub Desktop.
import * as React from 'react'
import {StringInputProps, useClient, useFormValue} from 'sanity'
export const ReadOnlyIfPublished = (props: StringInputProps) => {
const client = useClient({ apiVersion: '2021-03-25', })
const docId = useFormValue(['_id']) as string
const createdAt = useFormValue(['_createdAt'])
const [readOnly, setReadOnly] = React.useState(createdAt !== undefined)
React.useEffect(() => {
if (docId && docId.startsWith('drafts.')) {
const publishedId = docId.split('drafts.')[1]
client.getDocument(publishedId).then((result) => {
setReadOnly(result !== undefined)
})
} else {
setReadOnly(createdAt !== undefined)
}
}, [client, docId, createdAt])
return props.renderDefault({
...props,
elementProps: {
...props.elementProps,
readOnly,
},
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment