question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

React hooks + @apollo/hooks

See original GitHub issue

Hi, how would the React wrapper work in combination with @apollo/hooks?

At some point in my application, I would like to add an additional header with my access token if the user decided to log in. Some graphql queries should be available when the user isn’t logged in. So I have a scenario where I want to add the header only at a later point.

More to the point, consider the following code:

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

const setAuthorizationLink = setContext((request, previousContext) => {
  // get hook??
  // get accessToken somehow???
  return {
    headers: { authorization: "1234" }
  };
});

export function createApolloClient() {
  const httpLink = new HttpLink({
    uri: "/api/graphql"
  });

  const link = setAuthorizationLink.concat(httpLink);

  return new ApolloClient({
    link,
    cache: new InMemoryCache()
  });
}

How do I get my bearer token inside the setContext callback?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:8 (3 by maintainers)

github_iconTop GitHub Comments

12reactions
nojafcommented, Jul 15, 2019

Found another way:

import { Auth0Provider } from "./react-auth0-wrapper.js"
import { ApolloProvider } from "@apollo/react-hooks";
import { createApolloClient } from "./helper.js";

const ApolloWrapper = ({children}) => {
   const { getTokenSilently, loading  = useAuth0();
   const apolloClient = useMemo(() => createApolloClient(getTokenSilently), [loading]);
   return <ApolloProvider client={apolloClient>{children</ApolloProvider>
}

const App = () => {
   return <Auth0Provider {...}>
        <ApolloWrapper><h1>my app</h1></ApolloWrapper>
    </Auth0Provider >
}

helper.js

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

export function createApolloClient(getToken) {
  const httpLink = new HttpLink({
    uri: "/api/graphql"
  });

  const setAuthorizationLink = setContext((_, { headers }) => {
    return getToken().then(token => {
      debugger;
      console.log(`TOKEN:${token}`);
      return {
        headers: {
          ...headers,
          authorization: token ? `Bearer ${token}` : null
        }
      }
    });
  });

  const link = setAuthorizationLink.concat(httpLink);

  return new ApolloClient({
    link,
    cache: new InMemoryCache()
  });
}

1reaction
nirvdrumcommented, Oct 14, 2019

@nojaf I’ve tried out your solution, but it’s not working and I don’t see how it can. I believe it did work for you, so I’m not sure if I’m just overlooking something or if the SPA React wrapper changed. Any help you can provide would be much appreciated.

The problem is the getTokenSilently reference is invalid while Auth0 loading is true because the auth0Client reference is undefined until loading is false. Just to be clear that we’re looking at the same thing, I’m referring to the the provider’s getTokenSilently value, like in https://github.com/auth0-samples/auth0-react-samples/issues/142#issuecomment-511470797.

So, I’m uncertain how the useMemo call you have can work. Did you update the wrapper so that the provider always passes down a Promise for getTokenSilently?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Hooks - Apollo GraphQL Docs
The ApolloProvider component leverages React's Context API to make a configured Apollo Client instance available throughout a React component tree.
Read more >
@apollo/react-hooks - npm
React Apollo Hooks.. Latest version: 4.0.0, last published: 2 years ago. Start using @apollo/react-hooks in your project by running `npm i ...
Read more >
Use Apollo Client as React hooks - GitHub
Similar to ApolloProvider from react-apollo. Both packages can be used together, if you want to try out using hooks and retain Query ,...
Read more >
Apollo useQuery React hook - Hasura
Apollo useQuery React Hook. The recommended method is to use the useQuery React hook, where you will just pass your GraphQL query and...
Read more >
React Hooks in Apollo Client for GraphQL Queries and ...
The Apollo Provider enables us to use React Hooks for executing queries and mutations in our application. The following Hooks are available in...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found