Global `loading` indicator

I have a React app that makes heavy use of Apollo-Client and I’m wondering if there is a way to globally detect if Apollo is loading.

I have loading indicators for most of the site e.g. loading pages, spinners on buttons etc… but I want to setup something that will popup in the corner every time a query or mutation is running, even on refetch.

Is this possible? I’ve had a look at the docs and can’t find anything on the client that suggests there is a global query status like this.

Not sure if there’s a ready-made package, but one way to do it is to create a link that wraps the http link.

Something like (untested)

import {from} from '@apollo/client'
import {getMainDefinition} from '@apollo/client/utilities'

const loadingLink = new ApolloLink(async (operation, forward) => {
  if (!forward) {
    throw new Error('Cannot be the last link in the chain.')
  }
  // determine if operation is loading-notification-worthy
  // e.g. maybe not subscriptions
  const definition = getMainDefinition(operation)
  const isLoading = (
    definition.kind === 'OperationDefinition' &&
    definition.operation !== 'subscription'
  )
  // some counter
  globalIsLoadingIncrease()
  const out = await forward(operation)
  globalIsLoadingDecrease()
  return out
}

// ...get httpLink, then
const link = from([loadingLink, httpLink])
// ...then use link in ApolloClient
1 Like

I found the link example that talked about timing the queries and adapted that.

I now have something like this that updates another context on query start and end so that a status indicator can be shown/hidden as needed.

I’ll write it up once I get it tidied up.