Take the following queries:
import gql from "graphql-tag";
const FOO = gql` {
foo (id: "12") {
id
qux {
id
}
}
}
const BAR = gql` {
BAR (id: "12") {
id
qux {
id
}
}
}
It would be nice if we could keep the code DRY and define qux once.
I see two solutions:
qux out of the queries and define it a string. Here's a GitHub gist.But going with #2 comes with a caveat:
If you are using fragments on unions and interfaces, you will need to use an IntrospectionFragmentMatcher
What are the benefits of using fragments?
The Apollo docs are a bit misleading there. Using interfaces or unions will require you to provide an IntrospectionFragmentMatcher, period. That's because an inline fragment is still a fragment. If you're querying a union or interface field, you're going to have to use a fragment per concrete type, inline or otherwise. So I wouldn't really consider this a "caveat" of utilizing fragments.
You should generally use fragments for a couple of reasons:
graphql-tag everywhere. Most IDEs support syntax highlighting and other goodies for GraphQL documents stored this way.The main benefit of using string interpolation is the ability to easily include or exclude fields conditionally. This is still possible with fragments by utilizing the @skip and @include directives, but is much more verbose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With