NextJS header - Contentful Data

256 views Asked by At

I would like to present "Recent Articles" in my header menu "Learn", but since I'm using NextJS I cannot use getStaticProps in a custom component. How can I pass my GraphQL query from my articles page to my custom components?

Can anyone help me with an example where getStaticProps are used on a page and passed down to a custom component?

This is is my getStaticProps section of my articles.jsx file with the import on top:

import {
  getPaginatedArticles,
  getPaginatedCases,
  getArticles,
  getRecentArticles,
} from "../utils/contentful";

export async function getStaticProps() {
  const articles = await getPaginatedArticles();
  const cases = await getPaginatedCases();
  const categories = await getArticles();
  const recentArticles = await getRecentArticles();

  return {
    props: {
      articles: articles.articleCollection.items,
      cases: cases.caseCollection.items,
      categories: categories.articleCollection.items,
      recentArticles: recentArticles.articleCollection.items,
    },
  };
}

This the recentArticles query from import above:

export async function getRecentArticles() {
  const recentArticlesQuery = gql`
    {
      articleCollection(order: date_DESC, limit: 3) {
        items {
          title
          slug
          excerpt
          date
          contentfulMetadata {
            tags {
              name
              id
            }
          }
          featuredImage {
            title
            url
            width
            height
          }
          author {
            name
            photo {
              fileName
              url
              width
              height
            }
            title
            twitterProfile
            linkedInProfile
            slug
          }
        }
      }
    }
  `;
  return graphQLClient.request(recentArticlesQuery);
}

As mentioned in the beginning, it works if I use it within the article page, but I would like to use it in my header.

This is a simplified version of my Learn menu within my header custom component:

export default function Header() {
  return (
   <div>
     <h3>Recent Posts</h3>
       <ul>{recentPosts.map((post) => (
         <li
          key={post.id}>
            <a href={post.href}>
              {post.name}
            </a>
         </li>
         ))}
       </ul>
  </div>
 )                                 
}

How can I bring in the data to my custom header component from the articles.jsx file?

0

There are 0 answers