user13101751
user13101751

Reputation:

ApolloClient client's Type

I have a function where I pass the client as a parameter and delete the token from my app etc:

  const logOut = async (client: ApolloClient<unknown>) => {...};
return (
    <ApolloConsumer>
      {(client: ApolloClient<unknown>) => (
        <SafeAreaView style={styles.safeAreaViewContainer}>
                <View style={styles.buttonContainer}>
                <Button
                  onPress={() => logOut(client)}
                  style={styles.button}
                />
              </View>
             </SafeAreaView>
      )}
    </ApolloConsumer>
  );
};

Right now I am using unknownfor the ApolloClient type and it works. But what should I actually be using here?

Upvotes: 2

Views: 2212

Answers (1)

Nir Tamir
Nir Tamir

Reputation: 131

If you look at @apollo/client/react/context/ApolloConsumer.d.ts, you can see that the type of the client is ApolloClient<object> (in older react-apollo the type was ApolloClient<any>)

import React from "react";
import { ApolloClient } from "../../core";
export interface ApolloConsumerProps {
  children: (client: ApolloClient<object>) => React.ReactChild | null;
}
export declare const ApolloConsumer: React.FC<ApolloConsumerProps>;
//# sourceMappingURL=ApolloConsumer.d.ts.map

I would not specify the client's type explicitly. TypeScript is smart enough to infer it automatically.

If you still want to write a stricter type, the generic in ApolloClient is TCacheShape, and it depends on the cache you use with apollo.

For example, you are using InMemoryCache, the generic type is NormalizedCacheObject

export interface NormalizedCacheObject {
  [dataId: string]: StoreObject | undefined;
}

export interface StoreObject {
  __typename?: string;
  [storeFieldName: string]: StoreValue;
}

Upvotes: 4

Related Questions