Search code examples
reactjsgatsby

Gatsby issue - The list of posts didn't show up despite no errors shown under console and no error with Graphql


Background: Newbie...Learning React + Gatsby on weekend

Problem: What i'm trying to achieve here is - If the post equal to "blog" tag, generate a list of post with title. When i try to console.log(tag.name), i could see those tags under console (no errors) but nothing shows up on webpage (if it works well, there should be a list of post). I changed the array index but it wasn't working too. Appreciate if you could share what went wrong?

      <ul>
          {wpPosts.map(wpPost => {
            wpPost.tags.nodes.map(tag => {
              console.log(tag.name)

              if (tag.name === "Blog") {
                return (
                  <div>
                    <li>{tag.title}</li>
                  </div>
                )
              }
            })
          })}
        </ul>



  const data = useStaticQuery(
    graphql`
      query {
        allWpPost(sort: { fields: date, order: DESC }, limit: 10) {
          nodes {
            excerpt
            slug
            uri
            title
            date(formatString: "MMMM DD, YYYY")
            tags {
              nodes {
                name
              }
            }
          }
        }
      }
    `
  )

  const wpPosts = data.allWpPost.nodes

Solution

  • You are not returning the second map loop:

      <ul>
          {wpPosts.map(wpPost => {
            return wpPost.tags.nodes.map(tag => {
              console.log(tag.name)
    
              if (tag.name === "Blog") {
                return (
                  <div>
                    <li>{tag.title}</li>
                  </div>
                )
              }
            })
          })}
        </ul>