skip to Main Content

My problem is that object is very deep and somewhere I make a mistake that I cannot see. I want to display related post to post which someone click. I fetch date by GraphQL via WordPress to headless cms nextjs page.

in one component I have selected categories

  const postCategory = post.categories.edges[0].node.name

and this posts with this category I want to display as related posts:

posts.
filter((cat) => { return(
            cat.categories.edges.map((z) => z.node.name == postCategory)
         
        )})

anyone make similar project and see my mistakes?

2

Answers


  1. Perhaps do like this:

    const filteredPosts = [];
    
    for (const post in posts) {
      for (const edge in post.categories.edges) {
        if (edge.name == postCategory) {
          filteredPosts.push(post);
        }
      }
    }
    

    Keep things simple. Using those modern syntaxes in such a nested way only confuses people.

    Login or Signup to reply.
  2. You can have your query structure like this:

     categories {
                nodes {
                  name
                  posts {
                    nodes {
                      title
                    }
                  }
                }
              }
    

    and filter it like this

     const postsByCategory = post.categories.nodes[0].posts.nodes.slice(0, 4);
    
      const relatedPosts = postsByCategory.filter((relPost) => relPost.title !== post.title);
    

    I wanted only 3 results after excluding the current post.

    hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search