Apollo Client 3 - Global Event Listener?

Viewed 264

Is there a way to create a "global" event listener in Apollo Client 3?

For example if a user makes a section in the app, I want the "global event listener" to fire off some additional graphql requests to populate the app data according to the selection made.

I know for a simple app, I could have whichever component that is reading the app data to listen for the Reactive Variable so that when it changes (using useEffect) it fires off the useQuery hook. I don't want to do this in a specific component since this app data is used globally by several component and I don't want to repeat that logic in every one or have one component be responsible for it (in case that component is not used).

I know with React Redux, during store configuration, I can pass in an additional custom middleware that allows me to listen to for all actions and catch/match the ones I'm interested in, which therefore allowed me to fire off additional API requests and fire off actions (with the payload) when they return. I basically want to execute this same pattern, but with Apollo Client 3.

One way I found to make this work was to create a wrapper component around my entire app. This wrapper component is basically a pass-through component that then listens for reactive variables

export const AppStateListener: React.FC = ({children}) => {
  const [getData, { loading, data }] = useLazyQuery(GET_DATA);
  const selectedOption = useReactiveVar(selectedOptionVar)
  useEffect(() => {
    if(selectedOption)
      getData()
  }, [selectedOption?.id])

  return <>{children}</>
}

This seems to functionally work, but seems like a very hacky way of doing it. Does anyone know if there is a configuration I could tap into that allows me to listen for value changes so I can fire off other graphQl requests?

1 Answers

Seems like a cool idea, however apollo itself is already giving you a context to work with, isn't it possible to just use that:

const Apollo = ({children}) => {
  // all your reactive stuff here

  return <ApolloProvider client={client}>
    {children}
  </ApolloProvider>
}

However I have no idea if the context needs to be initialized before you can use the reactive variables.

Related