Search code examples
reactjstypescriptgraphqlgatsbycontentful

contenful and gatsby js fetching


I am trying to fetch data from contentful by using graphql in gatsby app , this is how I am doing it :

type AllContentfulBlogs = { 
    allContentfulBlogs: {
            nodes: Array<{
            title?: string | null | undefined,
            tag?: string | null | undefined,
            read?: string | null | undefined,
            date?: string | null | undefined,
            picture?: Array<{
            gatsbyImageData: any } | null | undefined> | null | undefined,
            }> 
        };
}
interface BlogProps {
    data: AllContentfulBlogs;
  }

function BlogsIndex({data: {
    allContentfulBlogs:{nodes}
},}:BlogProps) {
  return (
    <Layout>
        <div>
            {nodes}
        </div>
        <Blogs  />
    </Layout>
  )
export const query = graphql`
query BlogsQuery {
allContentfulBlogs {
    nodes {
      title
      tag
      picture {
        gatsbyImageData
      }
      read
      date
    }
  }
}
`

So when I try for example implementing nodes.title I get an error :

Property 'title' does not exist on type '{ title?: string | null | undefined; tag?: string | null | undefined; read?: string | null | undefined; date?: string | null | undefined; picture?: ({ gatsbyImageData: any; } | null | undefined)[] | null | undefined; }[]'

How can I fix this please ??


Solution

  • The problem is in your destructuring. BlogProps applies to data while you are getting nodes, which is an array.

    This approach is much simpler but should work:

    type AllContentfulBlogs = {
      allContentfulBlogs: {
        nodes: Array<{
          title?: string | null | undefined,
          tag?: string | null | undefined,
          read?: string | null | undefined,
          date?: string | null | undefined,
          picture?: Array<{
            gatsbyImageData: any } | null | undefined> | null | undefined,
        }>
      };
    }
    
    interface BlogProps {
      data: AllContentfulBlogs;
    }
    
    function BlogsIndex({data}:BlogProps) {
      return (
        <Layout>
          <div>
            {data.allContentfulBlogs.nodes[0].title}
          </div>
          <Blogs  />
        </Layout>
      )
      export const query = graphql`
        query BlogsQuery {
          allContentfulBlogs {
            nodes {
              title
              tag
              picture {
                gatsbyImageData
              }
              read
              date
            }
          }
        }
      `