Apollo-client: How to update ApolloClient after login?

Created on 21 Jan 2018  路  5Comments  路  Source: apollographql/apollo-client

Hi, I'm trying to do token based authentication for my app, I have something like this

async function getHttpLink() {
  const httpLink = createHttpLink({
    uri: `${hostUrl()}/graphql`
  });
  const token = await getAuthToken();
  const authLink = getAuthLink(token);

  return new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache()
  });
}

function getAuthLink(token) {
  const authLink = setContext((_, { headers }) => {
    return {
      headers: {
        ...headers,
        authorization: token ? `Bearer ${token}` : null,
        test: "test"
      }
    };
  });
  return authLink;
}

then in my main.js I have something like this

  setApolloClient = async () => {
    try {
      await getHttpLink().then(client => {
        this.setState({
          client
        });
      });
    } catch (e) {
      console.log(e);
    }
  };

  render() {
    const Layout = RootNavigator(signedIn, this.isCustomerVerified());
    return (
      <ApolloProvider client={this.state.client}>
        {/*<Layout screenProps={{ setApolloClient: this.setApolloClient }} />*/}
        <Layout />
      </ApolloProvider>
    );
  }

Intended outcome:
So the plan is before the user is signed in, the token is nil

After sign in happens, the headers will get the newly created auth token from AsyncStorage.

Actual outcome:
When I check the headers in the servers, token is still nil. I'm pretty sure the token is stored in AsyncStorage as when I refresh it goes skips the login page and goes straight to the home page.

Version

Thanks in advance for any help given, please tell me if you need any more info!

Most helpful comment

return new ApolloClient({
cache,
uri: Api.GRAPH_QL_URL,
clientState: {defaults, resolvers},
request: async operation => {
console.log("Client request: ", {
operationName: operation.operationName,
variables: operation.variables,
query: operation.query
});
let token = await AsyncStorage.getItem(strings.keyToken);
operation.setContext({
headers: {
Accept: "application/json",
authorization: token ? JWT ${token} : ""
}
});
}
});

check the request option

All 5 comments

This seems difficult to debug without more of the surrounding code, but here are a few things to try:

  • Log the value of the token after you await getAuthToken and make sure it is defined
  • Examine the network request sent by the browser to the server and make sure that it is formed as you expect it. I see you have a "test" header - is that sent to the server correctly?

Let us know if the steps outlined in https://github.com/apollographql/apollo-client/issues/2897#issuecomment-360747092 helped. Closing for now due to inactivity, but happy to re-open if this is still an issue. Thanks!

return new ApolloClient({
cache,
uri: Api.GRAPH_QL_URL,
clientState: {defaults, resolvers},
request: async operation => {
console.log("Client request: ", {
operationName: operation.operationName,
variables: operation.variables,
query: operation.query
});
let token = await AsyncStorage.getItem(strings.keyToken);
operation.setContext({
headers: {
Accept: "application/json",
authorization: token ? JWT ${token} : ""
}
});
}
});

check the request option

I think you can just call await client.resetStore();, right?

The information here helped me out.

https://spectrum.chat/apollo/apollo-client/need-help-with-a-mutation-and-refetchqueries~7b11b0e7-71a1-4974-8d34-582f4463e41a

I saved my auth token in the Mutation update callback instead of the onCompleted or the chained mutation promise.

Was this page helpful?
0 / 5 - 0 ratings