theRDnotes

2020 February 15th

Part6: Blog posts list

In this post, we will use GraphQL to fetch the details of our posts and show them as a list on index page.

We'll add the following to src/pages/index.js file.

  • GraphQL query to fetch details of blog posts that we created in the last post.
  • Code to render the list of posts.
import React from 'react';
import { Layout } from '../components/Layout';
import { graphql, Link } from 'gatsby';

export default ({ data }) => {
    return (
        <>
            <Layout>
                {
                    data.allMarkdownRemark.edges.map(post => {
                        const { title, author, date_modified, description } = post.node.frontmatter;
                        const { slug } = post.node.fields;
                        const excerpt = post.node.excerpt;
                        return (
                            <>
                                <p>{date_modified}</p>
                                <Link to={slug}>
                                    <h2>{title}</h2>
                                </Link>
                                <p>{description}</p>
                                <br/>
                            </>
                        )
                    })
                }
            </Layout>
        </>
    );
};

export const query = graphql`
query SiteIndexQuery {
    allMarkdownRemark(
        sort: { fields: [frontmatter___date_modified], order: DESC }
        filter: {frontmatter: {published: {eq: true}}}) 
        {
      edges {
        node {
          id
          excerpt
          fields {
              slug
          }
          frontmatter {
            title
            path
            date_modified
            author
            description
            published
          }
        }
      }
    }
  }
`;

In the above code, we have used Layout component which is simple wrapper to have a common layout across our blog.

The src/components/Layout.js file should have following contents:

import React from 'react';
import { useSiteMetadata } from '../hooks/useSiteMetadata';

export const Layout = ({ children }) => {
  const { title, description } = useSiteMetadata();
  return (
    <div style={{width: '680px', margin: '0 auto'}}>
      {children}
    </div>
  );
};

Restart the server npm run dev and head to http://localhost:8888/ to see the rendered listing of our posts.

But clicking on any post will result in a 404 default error page. Because we haven't processed our markdown files yet.

In the next post, we'll create a template with which we'll generate individual pages for the blog posts.