0
votes

Here's my sample graphql query for fetching user details(I use Apollo client in reactJS)

If i need only id and name as response i use this query

{
 getUserDetails {
   id
   name
 }
}

or if I need only id and userType i use this query:

{
 getUserDetails {
   id
   userType
 }
}

Is there any way i can pass the fields name and userType dynamically(Basically passing fields dynamically) instead of writing entire query again?

1
You can however write a function that builds the query for you in run time - junwen-k

1 Answers

3
votes

You could build a query at run time but generally it is adviced against (for reasons I don't want to get into here). Instead GraphQL comes with other solutions to the problem:

Generally GraphQL works well with React and composes in similar ways. GraphQL comes with fragments that can help with composing queries. Fragments are the equivalent of components in React. In cases where you have two different React components it should be fine to write two queries. I don't think that there is a reason to reuse queries.

Then there are interfaces/unions. So maybe you have a page where you want to show a user and depending on if you are friends or not with the user you want to show different things:

{
  getUserDetails {
    id
    name
    ...on UserFriend {
      friendsSince
    }
    ...on UserStranger {
      numberCommonFriends
    }
  }
}

If this is not the case and you really have a component with different data dependencies depending on some kind of input, don't be afraid of overfetching. Sure GraphQL claims to get rid of overfetching but you example seems so trivial that I would not introduce complexity for this.

Okay so you say your question is just an example! What if you want to conditionally load some expensive fields when there is a certain flag set. Then you can use directives:


const MyComponentQuery = gql`
  query MyComponentQuery($versionA: Boolean!) {
    {
      getUserDetails {
        id
        name @inlude(if: $versionA)
        userType @skip(if: $versionA)
      }
    }
  }
`;

function MyComponent(props) {
  const { data, loading, error } = useQuery(MyComponentQuery, {
    variables: { versionA: props.versionA },
  });

  return //...
}