Skip to content

Instantly share code, notes, and snippets.

@scottopolis
Created November 26, 2019 16:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottopolis/38c515be25d41d41c45034d9588499e0 to your computer and use it in GitHub Desktop.
Save scottopolis/38c515be25d41d41c45034d9588499e0 to your computer and use it in GitHub Desktop.
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
@jkr86
Copy link

jkr86 commented Jan 9, 2022

manually xD

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment