0

I followed the tutorial, and got to the last section where you put the blog posts on a page and the page ends up with just an H1 tag and none of the posts, is anyone able to take a look at the code and tell me why it might not be working?

import Link from 'next/link'
import groq from 'groq'
import client from '../client'

const Index = (props) => {
    const { posts = [] } = props
    return (
      <div>
        <h1>Welcome to a blog!</h1>
        {posts.map(
          ({ _id, title = '', slug = '', _updatedAt = '' }) =>
            slug && (
              <li key={_id}>
                <Link href="/post/[slug]" as={`/post/${slug.current}`}>
                  <a>{title}</a>
                </Link>{' '}
                ({new Date(_updatedAt).toDateString()})
              </li>
            )
        )}
      </div>
    )
}

Index.getInitialProps = async () => ({
    posts: await client.fetch(groq`
      *[_type == "post" && publishedAt < now()]|order(publishedAt desc)
    `)
})

export default Index
Mac Dev
  • 83
  • 1
  • 3
  • 11
  • If you only see an h1, that means `posts` has no entries in the array or `slug` is falsey. I recommend you trying figure out why `posts` might be empty or why your posts' slugs are falsey. Use console logs to display the values. Use the Network panel of your browser to see the response of your groq query to determine if the problem is occurring before or after your call to Sanity. Ultimately, we need more context if we are going to be able to help you. – JLF Apr 01 '20 at 14:14

1 Answers1

1

I've found the issue because I had the same problem.

Quick solution.

(pages/index.js)

I Replaced this:

*[_type == "post" && publishedAt < now()]|order(publishedAt desc)

into this:

*[_type == "post"]|order(publishedAt desc)

Explain If you did the tutorial as me, you've didn't enter a date, and the query in the example is more complex.

To understand better, I used the Vision (http://localhost:3333/vision) section to replicate the first GROQ line. And then removed the extra parameters.

Hope this helps!