Skip to content

Instantly share code, notes, and snippets.

@iamkevingreen
Last active October 8, 2019 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamkevingreen/296a7b4be299bdcb4e602098e3ca7c52 to your computer and use it in GitHub Desktop.
Save iamkevingreen/296a7b4be299bdcb4e602098e3ca7c52 to your computer and use it in GitHub Desktop.
import React from 'react'
import { Router } from '@reach/router'
import { pageQuery, productQuery, articleQuery } from '../api/preview.js'
import Page from '../templates/page.js'
import Product from '../templates/product.js'
import Editorial from '../templates/editorial.js'
const sanityClient = require('@sanity/client')
const client = sanityClient({
projectId: 'testtest',
dataset: 'production',
useCdn: false, // `false` if you want to ensure fresh data
withCredentials: true
})
class PreviewPage extends React.Component {
constructor (props) {
super(props)
this.state = {
document: null,
type: null
}
}
componentDidMount () {
const queryDraft = `*[_id == "${this.props.document}"] {
...,
}`
const queryPreviewPage = `*[_id == "${this.props.document}"] {
${pageQuery}
}`
const queryPreviewProduct = `*[_id == "${this.props.document}"] {
${productQuery}
}`
const queryPreviewArticle = `*[_id == "${this.props.document}"] {
${articleQuery}
}`
client.fetch(queryDraft).then(response => {
this.setState({
type: response[0]._type
})
switch(response[0]._type) {
case 'page':
client.fetch(queryPreviewPage).then(res => {
this.setState({
document: res[0]
})
})
break
case 'product':
client.fetch(queryPreviewProduct).then(res => {
this.setState({
document: res[0]
})
})
break
case 'post':
client.fetch(queryPreviewArticle).then(res => {
this.setState({
document: res[0]
})
})
break
default:
return
}
}).catch(error => {
console.log('problem', error)
})
}
renderPreview() {
if (this.state.document) {
switch (this.state.type) {
case 'page':
return <Page pageContext={this.state.document} />
case 'product':
return <Product pageContext={this.state.document} />
case 'post':
return <Editorial pageContext={this.state.document} />
default:
break
}
}
}
render () {
return (
<div>
{this.renderPreview()}
</div>
)
}
}
const Previews = () => {
return (
<div>
<Router>
<PreviewPage path='/previews/:document' />
</Router>
</div>
)
}
export default Previews
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment