Skip to content

Option to hook in to warnAboutDataLossΒ #458

@trevor-scheer

Description

@trevor-scheer

πŸ‘‹ from the other side! We'd like to notify devs (at dev time) outside of the console where we'd normally see invariant warnings, etc. from Apollo Client. Would y'all be open to an option that allows us to provide a callback for when these issues occur?

There's a(n awful) path forward today using private API which I'll share for posterity but of course I'd rather not use it if it can be avoided. Thanks in advance!

import { ApolloErrorMessageHandler } from "@apollo/client/utilities/globals/invariantWrappers";
type ApolloErrorMessageHandlerType = NonNullable<
  (typeof window)[typeof ApolloErrorMessageHandler]
>;

// Either resolve to the handler we intend to wrap or reject after 5s
async function getApolloErrorHandlerOnWindowOrThrow(): Promise<ApolloErrorMessageHandlerType> {
  return Promise.race([
    new Promise<never>((_resolve, reject) => {
      setTimeout(() => {
        reject();
      }, 5000);
    }),
    new Promise<ApolloErrorMessageHandlerType>(resolve => {
      const interval = setInterval(() => {
        if (!!window[ApolloErrorMessageHandler]) {
          clearInterval(interval);
          resolve(window[ApolloErrorMessageHandler]);
        }
      }, 100);
    }),
  ]);
}

export async function interceptApolloErrorsInDevOnly(): Promise<void> {
  if (__DEV__) {
    try {
      const apolloErrorHandler = await getApolloErrorHandlerOnWindowOrThrow();
      const wrapped = (message: number, args: string[]) => {
        // notify!
        return apolloErrorHandler(message, args);
      };
      window[ApolloErrorMessageHandler] = wrapped as typeof apolloErrorHandler;
    } catch (error) {
      console.error(error);
    }
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    coreFeature requests related to core functionality

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions