Apollo Client 3: query returns results in Chrome's Network tab, but undefined in my app

Viewed 1673

I am fetching some data using @apollo/client v3. In Chrome's network tab (http results), I can see it returns data and errors (I am not worried about the error, I know why it is right now.):

{
    data: {workItems: [,…]},…},
    errors: [{message: "Error trying to resolve position."
}

However in my app, data returns undefined.

Here's my client config:

export const graphqlClient = new ApolloClient({
    cache: new InMemoryCache(),
    link: ApolloLink.from([
        onError(({ graphQLErrors, networkError }) => {
            if (graphQLErrors) {
                graphQLErrors.forEach(error =>
                    console.log(
                        `[GraphQL error]: ${JSON.stringify(error, null, 2)}`
                    )
                )
            }
            if (networkError) {
                console.log(`[Network error]: ${networkError}`)
            }
        }),
        apolloLink
    ])
})

And my query:

gql`
    query WorkItems($ppm: String) {
        workItems(where: { ppm: $ppm }) {
            ...WorkItemKanban
        }
    }
    ${workItemFragment.workItemKanban}
`

const useWorkItemListDataGraphql = (args: {
    query: DocumentNode
    variables: { parent: string } | { ppm: string }
}) => {
    const { variables, query } = args
    const { data, error, loading, refetch } = useQuery<
        { workItems: WorkItem[] },
        { parent: string } | { ppm: string }
    >(query, {
        pollInterval: 180000,
        variables
    })
  
    // data returns undefined, but error shows the same error as in Chrome's network tab
    return { ...data, error, loading, refetch }
}

I am not sure where to start to identify what goes wrong. Loading the data works when there is no error, but I reckon this is not normal behavior, it should always load the same as I can see in Chrome's tab.

1 Answers

As explained in Apollo documentation - Error policies

By default, the error policy treats any GraphQL Errors as network errors and ends the request chain

hence by default, Apollo client returns undefined if there is an error.

Adding errorPolicy: 'all' in the query's options, or in the client default options solves the problem.

Example:

const { loading, error, data } = useQuery(MY_QUERY, { errorPolicy: 'all' });
Related