Apollo GraphQL client data is undefined when using fragments

Apollo GraphQL client data is undefined when using fragments


0

I’ve a Next.js project using the Apollo GraphQL client 3.7.17, where the following code works for me:

  const { loading, data, error } = useQuery(gql`
  query GetTeamCurrentWeek($teamId: ID!) {
    team(id: $teamId, idType: DATABASE_ID) {
      teamMeta {
        currentweek
      }
    }
  }
`,
    {
      variables: {
        teamId: 715
      }
    }
  );

If however I change the query to use fragments, I get data ‘undefined’:

fragment teamCurrentWeek on RootQuery {
  team(id: $teamId, idType: DATABASE_ID) {
    teamMeta {
      currentweek
    }
  }
}
query GetTeamCurrentWeek($teamId: ID!) {
  ...teamCurrentWeek
}

I’m querying WordPress using GraphQL and if I put the same query using fragments into the GraphiQL IDE, it works as expected and returns the same data as the non-fragments one, so it looks like the syntax/underlying data structure is all correct.

What is it about how I’m using it here that stops the query with fragments working?

Share
Improve this question

1 Answer
1

Reset to default


0

You need to import your fragment inside the query you want to use:

export const F_CURRENT_USER = gql`
  fragment FCurrentUser on Person {
    id
    name
    email
    validated
    loginIdentity
  }
`;



export const LOGIN_MAIL_MOBILE = gql`
  ${F_CURRENT_USER}
  mutation loginMailMobile($data: LoginCmsInput) {
    loginMailMobile(data: $data) {
      accessToken
      refreshToken
      user {
        ...FCurrentUser
      }
    }
  }
`;

Notice the ${F_CURRENT_USER} part

Share
Improve this answer



Leave a Reply

Your email address will not be published. Required fields are marked *