0
votes

I am trying to use fragments to reuse my graphql code but its not working although before using fragment code works fine.

This is how my code looks like

fragments.js

import gql from 'graphql-tag';

export const postFragment = gql`
    fragment PostData on postsConnection {
        edges {
            node {
                id
                title
                date
                featuredImage {
                    sourceUrl
                }
            }
        }
    } `

this is my query file queries/posts.js

import gql from 'graphql-tag';
import {postFragment} from '../fragments';


export const getAllPosts = gql`
  query getAllPosts {
    posts {
      ...PostData
    }
  }
  ${postFragment}
`;

This is the error get

[GraphQL error]: Message: Unknown type "postsConnection"., Location: [object Object], Path: undefined

How can i fix this?

1

1 Answers

2
votes

From the spec:

Fragments must specify the type they apply to... Fragments cannot be specified on any input value (scalar, enumeration, or input object). Fragments can be specified on object types, interfaces, and unions. Selections within fragments only return values when concrete type of the object it is operating on matches the type of the fragment.

A fragment must specify the type it applies to, and that type must actually exist in your schema. Based on the error you're seeing, postsConnection is not a valid type. Check the documentation for your schema or run an introspection query to determine the correct type for the posts field.

A simple introspection query to get the names and types of all fields for the Query type:

query GetQueryFields {
  __schema {
    queryType {
      fields {
        name
        type {
          name
          kind
        }
      }
    }
  }
}