Search code examples
javascripttypescriptgraphqlapolloapollo-client

How to properly handle loading and partial states when executing a GraphQL query using ApolloClient?


I'm working on a backend application that gathers data from GraphQL endpoints and I'm using ApolloClient to do so:

const client = new ApolloClient({
    uri: uri,
    link: new HttpLink({ uri: uri, fetch }),
    cache: new InMemoryCache({
        addTypename: false,
    }),
});

When I use the query function:

client.query({
    query: query,
    variables: vars,
    fetchPolicy: "no-cache",
})

it returns an ApolloQueryResult object:

ApolloQueryResult<T> = {
    data: T;
    errors?: ReadonlyArray<GraphQLError>;
    error?: ApolloError;
    loading: boolean;
    networkStatus: NetworkStatus;
    partial?: boolean;
}

My problem is that I've checked the docs and it doesn't say how I should handle loading and partial states. I'm not using React and I have the impression that these are only used for frontend calls, but I want to be sure.

I tested it and partial and loading is always undefined for me, no matter what endpoint I call.

What is the proper way to handle these from node? Can it happen that these are not undefined?


Solution

  • I have been curious about this myself, so I had a look at the source.

    loading: [can ignore] The query method you are calling on ApolloClient never sets result.loading to true. The front-end React useQuery hook does, which makes sense because its job is to help with the UI renders.

    partial: [depends] The ApolloQueryResult typedef source includes the following comment: "If result.data was read from the cache with missing fields, result.partial will be true...". You client is configured to use a cache, but the query has a no-cache policy.