Skip to content

Instantly share code, notes, and snippets.

@SimeonGriggs
Last active March 3, 2022 15:51
Show Gist options
  • Select an option

  • Save SimeonGriggs/59fe0a41b9bd3fa55ca24bc7a527d54f to your computer and use it in GitHub Desktop.

Select an option

Save SimeonGriggs/59fe0a41b9bd3fa55ca24bc7a527d54f to your computer and use it in GitHub Desktop.
Document action to toggle an `isLive` field with double-confirmation
import {useState, useMemo, useEffect} from 'react'
import {useDocumentOperation} from '@sanity/react-hooks'
import {FiZap, FiZapOff} from 'react-icons/fi'
export function ToggleLive({id, type, draft, published, onComplete}) {
const {patch, publish} = useDocumentOperation(id, type)
const doc = useMemo(() => draft || published, [draft, published])
const [isPublishing, setIsPublishing] = useState(false)
const [dialogOpen, setDialogOpen] = useState(false)
useEffect(() => {
if (isPublishing && !draft) {
setIsPublishing(false)
}
}, [draft])
const isLive = Boolean(published?.live)
// Return null so the Action does not appear at all until published
if (draft) return null
return {
disabled: false,
dialog: dialogOpen && {
type: 'confirm',
color: 'success',
onCancel: () => onComplete(),
onConfirm: () => {
patch.execute([{set: {live: !isLive}}])
publish.execute()
onComplete()
},
message: isLive
? `Hide ${`"${doc.title}"` ?? `this Document`} from being queried?`
: `Make ${`"${doc.title}"` ?? `this Document`} publicly available?`,
},
// eslint-disable-next-line no-nested-ternary
label: isPublishing ? 'Updating...' : isLive ? `Remove Live` : `Make Live`,
icon: isLive ? FiZapOff : FiZap,
onHandle: () => {
setIsPublishing(true)
setDialogOpen(true)
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment