I have this in my complicated app:
JavaScript
x
35
35
1
import { gql } from '@apollo/client';
2
3
gql`
4
fragment StuffTable on Stuff {
5
id
6
status
7
}
8
`;
9
10
export const GetStuffDocument = gql`
11
query GetStuff($id: ID!) {
12
stuff(id: $id) {
13
id
14
...StuffTable
15
}
16
}
17
`
18
19
// Then in another file:
20
import { ApolloClient, useApolloClient } from '@apollo/client';
21
import GetStuffDocument from './OtherFile';
22
23
async function exportStuff(client: ApolloClient<unknown>): Promise<void> {
24
const { data: metadata } = await client.query<GetStuffQuery>({
25
query: GetStuffDocument,
26
});
27
// other stuff, but it fails at the client.query step.
28
}
29
30
function MyComponent() {
31
const client = useApolloClient();
32
33
return <button onClick={() => exportStuff(client)}>Download</button>
34
}
35
Basically, I have an export button which will export a CSV of my GraphQL data. I manually call client.query to fetch the latest data on click of the button, but it throws an error saying it can’t find the used fragment StuffTable
. How do I include that fragment in the query?
I am getting this error:
JavaScript
1
12
12
1
Uncaught (in promise) Error: Fragment StuffTable was used, but not defined
2
at new ApolloError (index.ts:54:1)
3
at QueryManager.ts:1043:1
4
at both (asyncMap.ts:30:1)
5
at asyncMap.ts:19:1
6
at new Promise (<anonymous>)
7
at Object.then (asyncMap.ts:19:1)
8
at Object.next (asyncMap.ts:31:1)
9
at notifySubscription (module.js:132:1)
10
at onNotify (module.js:176:1)
11
at SubscriptionObserver.next (module.js:225:1)
12
How do I include the Fragment in my manual client.query
or whatever I need to do to resolve this error and get it to work?
Is there something like this I can do?
JavaScript
1
13
13
1
const StuffTableFragment = gql`
2
fragment StuffTable on Stuff {
3
id
4
status
5
}
6
`;
7
8
// then...
9
const { data: metadata } = await client.query<GetStuffQuery>({
10
query: GetStuffDocument,
11
fragments: [StuffTableFragment],
12
});
13
I’m looking at the docs but don’t see anything of help.
Advertisement
Answer
You’ll need to import the fragment into your query code. Instead of this:
JavaScript
1
15
15
1
gql`
2
fragment StuffTable on Stuff {
3
id
4
status
5
}
6
`;
7
8
export const GetStuffDocument = gql`
9
query GetStuff($id: ID!) {
10
stuff(id: $id) {
11
id
12
...StuffTable
13
}
14
}
15
You can do this:
JavaScript
1
16
16
1
const STUFF_TABLE_FRAGMENT = gql`
2
fragment StuffTable on Stuff {
3
id
4
status
5
}
6
`;
7
8
export const GetStuffDocument = gql`
9
${STUFF_TABLE_FRAGMENT}
10
query GetStuff($id: ID!) {
11
stuff(id: $id) {
12
id
13
...StuffTable
14
}
15
}
16
That will make sure that the fragment StuffTable is included in your query!