I am using react-native and apollo client and if I try to set header by jwt stored in AsyncStorage, it seems not working.
Other resolvers which doesn't need header works very well. My code is like below.
import { ApolloClient } from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { ApolloLink } from "apollo-link";
import { createHttpLink } from "apollo-link-http";
import AsyncStorage from "@react-native-community/async-storage";
const cache = new InMemoryCache();
const getToken = async () => {
const token = await AsyncStorage.getItem("jwt");
if (token) {
return token;
} else {
return null;
}
};
const httpLink = new createHttpLink({
uri: ""
});
const authLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
"X-JWT": getToken()
// this is where I set headers by getToken function
// If I change function getToken to real token in string type, it works then
}
});
return forward(operation);
});
const client = new ApolloClient({
cache: cache,
link: authLink.concat(httpLink)
});
export default client;
Like I commented in the code, calling getToken function is not working what I expected. I think I should have more knowledge of async and await, but I don't get it what is the real problem.
The error message I get from console is jwt malformed
. Please let me know how to fix this problem
async function
always returns a promise so you will get a pending promise. Can you try making the ApolloLink callbackasync
and set"X-JWT": await getToken()
– AccumulativeNetwork error: inner.subscribe is not a function
. @AsafAviv – Doleful