Last active
June 12, 2023 20:15
-
-
Save runeb/caa0d87f043529dc7e035c1142f6219b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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