Apollo-client: How to setup apollo-client with httpLink, errorLink and authLink.

Created on 17 Dec 2019  路  1Comment  路  Source: apollographql/apollo-client

  "react": "^16.11.0",
  "apollo-cache-inmemory": "^1.6.3",
  "apollo-client": "^2.6.4",
  "apollo-link-context": "^1.0.19",
  "apollo-link-error": "^1.1.12",
  "apollo-upload-client": "^12.1.0",
  "@apollo/react-hooks": "^3.1.3",

Here I'm facing a problem with setting up httpLink, errorLink and authLink together. I'm able to set up ApolloClient link with errorLink and httpLink link: errorLink.concat(httpLink) or authLink with httpLink. link: authLink.concat(httpLink),, Now how I'm supposed to set up with three links.

React Apollo Setup

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Router } from "react-router-dom";
import ApolloClient from "apollo-client";
import { ApolloProvider } from "@apollo/react-hooks";
import { InMemoryCache } from "apollo-cache-inmemory";
import { setContext } from "apollo-link-context";
import { createUploadLink } from "apollo-upload-client";
import { onError } from 'apollo-link-error';
import history from "./utils/history";

import * as serviceWorker from "./serviceWorker";

const httpLink = new createUploadLink({
  uri: "http://localhost:5000/graphql"
});

const errorLink = new 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}`);
});

const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem("token");
  return {
    headers: {
      ...headers,
      authorization: token
    }
  };
});

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

ReactDOM.render(
  <ApolloProvider client={client}>
    <Router history={history}>
      <App />
    </Router>
  </ApolloProvider>,
  document.getElementById("root")
);

serviceWorker.register();

Why I don't use apollo-boost?

  • I'm not able to set up apollo-upload-client with Apollo Boost thats why I use apollo-client

Most helpful comment

You should be able to do something like the following:

import { from } from '@apollo/client'

const client = new ApolloClient({
  cache,
  link: from([authMiddleware, errorLink, persistedQueriesLink, link]),
});

>All comments

You should be able to do something like the following:

import { from } from '@apollo/client'

const client = new ApolloClient({
  cache,
  link: from([authMiddleware, errorLink, persistedQueriesLink, link]),
});
Was this page helpful?
0 / 5 - 0 ratings