Last active
October 8, 2019 16:11
-
-
Save iamkevingreen/296a7b4be299bdcb4e602098e3ca7c52 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 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