Skip to content Skip to sidebar Skip to footer

How Can I Fetch Content From A Single Page Throught Contentful Api In A Nextjs Website?

I've found some guides here and there about sourcing from Contentful into NextJS, where you can feed a static blog with content. That's a starting point. But as for single pages co

Solution 1:

I had a lot of trouble figuring this out and thanks to @stefan-judis, who pointed out the misuse of getEntries and getEntry together, I had a lead on the approach that would work better for this.

It is, in fact, documented, but for beginner users like me, sometimes documentation on contentful can be a little weird to get, due to the wide number of APIs and methods on fetching content.

What I did that worked for me was to set an async function where I called the entries using queries. I'm used to query content with Gatsby using graphQL so I misunderstood the logic - like I said, no experience enough.

// client-contentful.js <-- This is a simple caller for the clientconst { createClient } = require('contentful')

const client = createClient({
  space: process.env.NEXT_PUBLIC_CONTENTFUL_SPACE,
  accessToken: process.env.NEXT_PUBLIC_CONTENTFUL_ACCESS_TOKEN
})

module.exports = client

// ***.jsimport client from'client-contentful.js'// Set content for the page exportasyncfunctiongetStaticProps() {
  let data = await client.getEntries({
    content_type: 'paginas', // <-- set content_type'fields.slug': 'inicio'// <-- filter the page with the slug (you can pass it as a props too)
  })
  return {
    props: {
      pagina: data.items[0] // <-- this will set the query as a prop
    }
  }
}

exportfunctionPage({ pagina }) {
  const { titulo, slug, section } = pagina.fieldsreturn (
        <mainid={slug}><h1>{titulo}</h1><RenderSectionsection={section} /></main>
    )
}

You can use this in many ways, as it is documented in other places. This is a solution I found out after some struggle.

Now, I still have a problem with the section part, where I have entries in my pages that I'd like to render in a mapping. Working on it right now.

Post a Comment for "How Can I Fetch Content From A Single Page Throught Contentful Api In A Nextjs Website?"