Search code examples
graphqlapolloreact-apollographiql

Querying graphiql leads Apollo error forward is not a function


I have an express back-end with GraphQL that works when I go to /graphiqland manually perform some searches. My React front-end is trying to perform a search on the back-end. The following code should perform the query asynchronously:

const data = await this.props.client.query({
    query: MY_QUERY,
    variables: { initials: e.target.value }
});
console.log(data);

Where MY_QUERY is defined before and represents a query that I know works and has been tested on /graphiql. To do this in my React component I export it as export default withApollo(MyComponent) so that it has the client variable in the props.

In the index.js file I defined through Apollo the connection to /graphiql in order to perform the queries:

//link defined to deal with errors, this was found online
const link = 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}`);
});

//the httpLink to my GraphQL instance, BASE_URL is defined elsewhere
const httpLink = new HttpLink({
    uri: BASE_URL,
    headers: {
    },
});

//here I define the client linking the GraphQL instance, the cache, and error handling
const client = new ApolloClient({
    link: httpLink,
    cache,
    link
});

When executing the above mentioned query without the linkvariable that handles the error, I receive a 400 Bad Request from the server (ApolloError.js:37 Uncaught (in promise) Error: Network error: Response not successful: Received status code 400). Since this doesn't tell me more, here on StackOverflow and on the Apollo Web page I've found the above error declaration that outputs [Network error]: TypeError: forward is not a function. What does this error mean and how do I solve it?

Thanks!


Solution

  • Your client configuration has a duplicate property -- you first set the link property to your HttpLink and then set it again to your ErrorLink. This means the HttpLink is ignored completely, and you're only passing in the ErrorLink to the configuration. You're seeing that error because the ErrorLink created by onError is not meant to be used by itself. Instead, it should be chained with the HttpLink and that's what you should assign to the link property.

    This page in the docs details how to correctly compose links. You can use concat but I prefer ApolloLink.from since it allows you to clearly show the order of your links:

    const errorLink = onError(...)
    const httpLink = new HttpLink(...)
    const link = ApolloLink.from([
      errorLink,
      httpLink,
    ])
    const client = new ApolloClient({
      link,
      cache,
    })