0
votes

I'm trying to handle errors on my React Native with Expo app, while using Apollo and Graphql. The problem is that in my apolloServices.js I'm trying to use onError function, and despite I tried with both apollo-link-error and @apollo/client/link/error the import is still greyed out. The function it's at the ApolloClient.

React-native: 0.63.2 @Apollo-client: 3.3.11 Apollo-link-error: 1.1.13

Image of the onError function greyed out, apparently not in use

// Apollo resources
import { HttpLink } from 'apollo-link-http';
import { ApolloClient } from '@apollo/client'; // Tried putting onError here
import { onError } from 'apollo-link-error'; // And here
//import { onError } from '@apollo/client/link/error'; // Also here
import {
  InMemoryCache,
  defaultDataIdFromObject,
} from 'apollo-cache-inmemory';
import { setContext } from 'apollo-link-context';

/* Constants */
import { KEY_TOKEN } from '../constants/constants';

/**
 * @name ApolloServices
 * @description
 *   The Apollo Client's instance. App.js uses it to connect to graphql
 * @constant httpLink HttpLink Object. The url to connect the graphql
 * @constant defaultOPtions Object. Default options for connection
 * @constant authLink
 */

const httpLink = new HttpLink({
  uri: 'workingUri.com',
});

const defaultOptions = {
  watchQuery: {
    fetchPolicy: 'no-cache',
    errorPolicy: 'ignore',
  },
  query: {
    fetchPolicy: 'no-cache',
    errorPolicy: 'all',
  },
};

//Create link with auth header
const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  return AsyncStorage?.getItem(KEY_TOKEN).then((token) => {
    // return the headers to the context so httpLink can read them
    return {
      headers: {
        ...headers,
        'auth-token': token ? token : '',
      },
    };
  });
});

export default new ApolloClient({
  /* ON ERROR FUNCTION HERE*/
  onError: (graphQLErrors, networkError) => {
    if (graphQLErrors)
      graphQLErrors.map(
        ({ message, locations, path }) =>
          console.log(
            `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
          ),
      );

    if (networkError) {
      console.log(`[Network error]: ${networkError}`);
    }
  },
  cache: new InMemoryCache(),
  defaultOptions: defaultOptions,
  link: authLink.concat(httpLink),

  request: (operation) => {
    operation.setContext({
      headers: {
        'auth-token': token ? token : '',
      },
    });
  },
});

Appart from this, the app is working perfectly, what I want it's just to handle graphql and network errors

1

1 Answers

1
votes

The best solution would be to use this approach


const errorControl =  onError(({ networkError, graphQLErrors }) => {
        if (graphQLErrors) {
            graphQLErrors.map(({ message, locations, path }) =>
                console.log(
                    " [GraphQL error]: Message", message, ", Location: ", locations, ", Path: ", path)
            );
        }
        if (networkError) {
            console.log(" [Network error]:", networkError)
        };

    });

export default new ApolloClient({

    cache: new InMemoryCache(),
    defaultOptions: defaultOptions,
    link: errorControl.concat(authLink.concat(httpLink)),

        headers: {
            authorization: token ? token : '',
        },
  });