So now that we've gone through the process of setting up connected mode, we can start leveraging GraphQL to build out some of the more dynamic components on the site. We'll be starting with the "Recent Posts" component to display a list of the newest posts that have been published.

Recent Posts Component

Here's what our rough query will look like:

src/components/RecentPosts/index.js

  {
    search(fieldsEqual:[{
      name:"_templatename"
      value:"Article-Template"
    },
    {
      name:"_fullpath"
      value:"/sitecore/content/blog*"
    }]
    first:5) {
      results {
        items {
          item {
            ... on ArticleTemplate {
              title {
                value
              }
              body {
                value
              }
            }
          }
        }
      }
    }
  }

We're using the Content Search API here to query articles. This query is flawed though. There's no actual way of sorting the results returned by the Content Search API currently so we're just going to roll with just receiving any five articles it happens to return. We'll explore expanding this functionality in a later post so we can properly sort the list.

Our query filters by two fields, first we're filtering by _templatename since we're only looking for items that are of template Article-Template. After that we're filtering by _fullpath since it's possible we'll get the standard values item returned if we don't. Filtering by the path /sitecore/content/blog* limits our scope to just content items. The other parameter we're passing in is first which puts a limit on the amount of items our query will return.

I created some generic PostListItem and PostListing components that we'll be using on other list pages. Leaving our RecentPosts implementation looking like this:

const RecentPosts = (props) => (
  <Query query={GET_RECENT_POSTS}>
    {({ loading, error, data }) => {
      if (loading) return "Loading...";
      if (error) return `Error! ${error.message}`;
      return (
        <PostListing posts={data.search.results.items} />
      );
    }}
  </Query>
);

We're able to leverage the React Apollo query component to handle doing the query for us, read more about that here: https://www.apollographql.com/docs/react/essentials/queries.html.

PostListing and PostListingItem are just standard react components so I won't go into depth explaining them. Check out the code for them here if you're interested in seeing them.

Conclusion

Overall, this component was pretty straight forward to implement. I built out the query using the included GraphiQL interface for my endpoint and after I had my query working as expected, I just plugged it into my component.

We will be circling back to this component to fix the sorting on it near the end of the implementation. Maybe we'll add some pagination in as well.