Apollo GraphQL client data is undefined when using fragments

237 Views Asked by At

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?

2

There are 2 best solutions below

1
SlothOverlord On

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

0
linucks On

The problem was that I was querying Wordpress with a fragment on the root query using WPGraphQL, and this sets the root query type to be RootQuery, which is different to that expected by Apollo Client. You therefore to configure the Apollo Cache as explained in the documentation.

The correct configuration of the Apollo Cache should be set as below:

const cache = new InMemoryCache({
  typePolicies: {
    RootQuery: {
      // The RootQueryFragment can only match if the cache knows the __typename
      // of the root query object.
      queryType: true,
    },
    RootMutation: {
      mutationType: true,
    },
  },
});