Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dynamic Content in Gatsby with Apollo and WPGraphQL
// This is just for example purposes, copy/pasting this won't work out of context. It is from the Gatsby Publisher theme by Static Fuse.
import React from 'react'
import { Box } from '@chakra-ui/core'
import Layout from '../../components/Layout'
import PostEntry from '../../components/PostEntry'
import Pagination from '../../components/Pagination'
import HeaderArchive from '../../components/HeaderArchive'
import SEO from '../../components/SEO'
import { useQuery } from '@apollo/react-hooks'
import gql from 'graphql-tag'
// This query is executed at run time by Apollo. The dateQuery is used to fetch any posts that were created after our most recent static build. Ideally this date would reset on each static build.
const APOLLO_QUERY = gql`
query {
posts(where: {dateQuery: {after: {day: 25, month: 11, year: 2019}}}) {
nodes {
id
postId
title
content
link
categories {
nodes {
name
slug
id
}
}
tags {
nodes {
slug
name
id
}
}
author {
name
avatar(size: 50) {
url
}
slug
}
}
}
}
`
// static posts are passed here (nodes) at build time, the normal Gatsby way
const BlogArchive = props => {
const {
pageContext: { nodes, pageNumber, hasNextPage, itemsPerPage, allPosts },
} = props
const { loading, error, data } = useQuery(APOLLO_QUERY)
return (
<Layout>
<SEO title="Posts" description="Blog posts" keywords={[`wordpress`]} />
<Box maxW="2xl" m="auto">
// If any dynamic posts need to be shown, they show up here
{ data && data.posts.nodes.length ? <HeaderArchive name={'Dynamic Posts'} /> : '' }
{data &&
data.posts.nodes.map(post => <PostEntry key={post.postId} post={post} />)}
<HeaderArchive name={'Static Posts'} />
// All static posts are displayed in this loop, like normal
{nodes &&
nodes.map(post => <PostEntry key={post.postId} post={post} />)}
<Pagination
pageNumber={pageNumber}
hasNextPage={hasNextPage}
allPosts={allPosts}
itemsPerPage={itemsPerPage}
/>
</Box>
</Layout>
)
}
export default BlogArchive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.