Skip to content

Instantly share code, notes, and snippets.

@SimeonGriggs
Created June 16, 2022 06:36
Show Gist options
  • Save SimeonGriggs/81b5fd22847f1f1b08f130316ffaed64 to your computer and use it in GitHub Desktop.
Save SimeonGriggs/81b5fd22847f1f1b08f130316ffaed64 to your computer and use it in GitHub Desktop.
A component to write predefined into an Array field
// Add to your schema like...
// {name: `pageBuilderTemplatePopulator`, type: `string`, inputComponent: TemplatePopulator},
import {Button, Grid} from '@sanity/ui'
import React, {useCallback, useState} from 'react'
import sanityClient from 'part:@sanity/base/client'
const client = sanityClient.withConfig({apiVersion: `2021-05-19`})
const contentData = [
{
_key: '58119fd04200',
_type: 'pageBuilderHero',
description: 'A short description',
image: {
_type: 'image',
asset: {
_ref: 'image-8ac7d96400d4d9a587b3c47a24267cc17b97d820-600x400-jpg',
_type: 'reference',
},
},
title: 'The title',
},
{
_key: '76f2273c5558',
_type: 'pageBuilderContent',
content: [
{
_key: '45eefbcf9ee2',
_type: 'block',
children: [
{
_key: 'd1926db2584e',
_type: 'span',
marks: [],
text: 'Here is some text content.',
},
],
markDefs: [],
style: 'normal',
},
],
lead: "A leading description of what you're about to see",
title: 'The whole story',
},
]
const imageData = [
{
_key: '58119fd04200',
_type: 'pageBuilderHero',
description: 'A short description',
image: {
_type: 'image',
asset: {
_ref: 'image-8ac7d96400d4d9a587b3c47a24267cc17b97d820-600x400-jpg',
_type: 'reference',
},
},
title: 'The title',
},
{
_key: '08bb5904dd67',
_type: 'pageBuilderImage',
image: {
_type: 'image',
asset: {
_ref: 'image-d2a440b42631d7dfd9e1bcc70be1ac920263c119-600x400-jpg',
_type: 'reference',
},
},
title: 'See for yourself',
},
]
const FIELD_TO_PATCH = `content`
export default function TemplatePopulator(props) {
const {parent} = props
const [isPatching, setIsPatching] = useState(false)
const handleClick = useCallback((data) => {
const documentId = parent._id
if (data) {
client
.patch(documentId)
.setIfMissing({[FIELD_TO_PATCH]: []})
.set({[FIELD_TO_PATCH]: data})
.commit()
.then((res) => {
setIsPatching(false)
})
} else {
client
.patch(documentId)
.unset([FIELD_TO_PATCH])
.commit()
.then((res) => {
setIsPatching(false)
})
}
}, [])
return (
<Grid columns={3} gap={4}>
<Button
disabled={isPatching}
tone="primary"
text="Content Template"
onClick={() => handleClick(contentData)}
/>
<Button
disabled={isPatching}
tone="primary"
text="Image Template"
onClick={() => handleClick(imageData)}
/>
<Button
disabled={isPatching}
tone="critical"
text="Reset"
onClick={() => handleClick(null)}
/>
</Grid>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment