typescriptapolloreact-apolloreact-apollo-hooks

Type 'DefaultClient<unknown>' is not assignable to type 'ApolloClient<object>'


I am trying to explicitly supply a client to useMutation. Everything works fine except for the fact that typescript seems to see a type mismatch.

Type 'DefaultClient<unknown>' is not assignable to type 'ApolloClient<object>'.

The client is very similar to the one shown in apollo's token authentication documentation

import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

const httpLink = createHttpLink({
  uri: '/graphql',
});

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem('token');
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

export const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

All I do really is import the client and supply it as an option to useMutation.

import {useMutation} from '@apollo/react-hooks'
import {client} from './client'

const MY_QUERY = `
  ...
`

const [myQuery] = useMutation(MY_QUERY, {
  client: client,
  onCompleted: () => {
    // do some stuff..
  }
})

useMutation seem to be expecting another type that the one that is inferred. How can I solve this mismatch ?


Solution

  • It seems like you should have InMemoryCache as type parameter:

    export const client = new ApolloClient<InMemoryCache>({
    

    I've tried to understand how this parameter is used, and I can't quite figure it out. Honestly, the empty object seems to work fine too:

    export const client = new ApolloClient<{}>({
    

    But when reading the source code it looks like it wants the cache type.