I have a server side rendered app and want data to be accessible on the first render. If a user navigates to the next page, I want to use the graphQL library Apollo to fetch the new content.
When a page is requested, the server sets the initialState key curPage with the data of the page that is requested. For example a user requests http://example.com/about. I get the page data for /about from my DB, set the initialState key curPage to that data from the DB.
So my initialState might look something like this:
{
"curPage": {
"id": 5,
"title": "About",
"slug": "about",
"path": "/about",
"template": "about",
"published": "2017-07-10 02:02:30",
"image": null,
"seo": {
"title": null,
"description": null,
"image": null,
"fbAdmins": null,
"gtm": null,
"schema": ""
},
"sections": [
{
"type": "masthead",
"mh_title": "",
"video": false,
"image": [
],
"showCta": false,
"cta": [
]
},
{
"type": "text_image",
"alignment": "left",
"text_image": [
{
"type": "text",
"title": "",
"content": "",
"call_to_action": false,
"cta": [
]
}
]
}
]
},
}
So if that curPage data is available, I want to use that, otherwise I want to fetch from graphQL.
My page component currently only fetches from graphQL and doesn't check if the data is available in initialState.
import React, { Component } from 'react'
import { graphql, gql } from 'react-apollo';
import './about.css'
class About extends Component {
render() {
return (
<section className='about-container'>
<h2>About Page</h2>
</section>
)
}
}
const mapQueryToProps = ({data: { findResource }, ownProps}) =>
({ curPage: findResource ? findResource[0] : null })
const MY_QUERY = gql`
query {
findResource(filter: {resource: "pages", slug: "about"}) {
id
title
slug
path
sections
}
}`
export default graphql(MY_QUERY, { props: mapQueryToProps })(About)
Is there a way through Apollo graphQL that I can do something like react-redux's connect() does but if it isn't available then fetch from graphQL?
I'm guessing I need to use connect() but then in my componentDidMount() check if the data is set and if it's not retrieve it?