Challenges

Using a CMS

Fetch Post List

Let's fetch the post list from GraphCMS & render it inside our app. For that, we use a tiny NPM module called graphql-request. Let's install that with:

yarn add graphql graphql-request

Now open the lib/data.js file & import graphql-request with:

import { GraphQLClient } from 'graphql-request'

Then create our an instance of GraphQLClient with:

const graphcms = new GraphQLClient(process.env.GRAPHCMS_API_URL)

Finally, replace the getPostList function with this:

export async function getPostList() {
    const { posts } = await graphcms.request(
        `
        query MyQuery {
            posts {
                title
                slug
                createdAt
                content
            }
        }          
        `
    )

    return posts.map(post => ({
        ...post,
        createdAt: (new Date(post.createdAt)).getTime()
    }))
}

(Here's the final version of the file after all these changes.)

Now you can see the list of blog posts when you visit the homepage.


Q: Here, we created the `createdAt` field manually, even though we fetch it via GraphQL. Why?
authenticating...

šŸ™ We need your help

We need your help to keep maintain & add new content to this course. Here's how you can support us: