Challenges

Using a CMS

Fetch a Single Post

Now, let's add support to fetch a single post.

To do that, open the lib/data.js file & replace the getPost function with this:

export async function getPost(slug) {
    const { post } = await graphcms.request(
        `
        query MyQuery($slug: String) {
            post(where: {slug: $slug}) {
                title
                slug
                createdAt
                content
            }
        }          
        `,
        { slug }
    )

    return {
        ...post,
        createdAt: (new Date(post.createdAt)).getTime()
    }
}

After that, you can view individual blog posts.


If you looked at the query carefully, you might have seen something different from what we created in the GraphCMS query builder. We created something like this inside the query builder:

query MyQuery {
    post(where: {slug: "hello-world"}) {
        title
        slug
        createdAt
        content
    }
}

So, why can't we use a query like this:

const { post } = await graphcms.request(
    `
    query MyQuery {
        post(where: {slug: "${slug}"}) {
            title
            slug
            createdAt
            content
        }
    }          
    `,
    { slug }
)

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

Q: Select the best answer?
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: