import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
const httpLink = createHttpLink({
uri: '/graphql',
});
const authLink = setContext((_, { headers }) => {
// get the authentication token from local storage if it exists
const token = localStorage.getItem('token');
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
}
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
In this line, const token = localStorage.getItem('token');
we mostly use async/await to get data from local storage, in that case authLink will be async function right?
i believe that means,
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
this lines run before we fulfill async httpLink function call, is not this a race issue? will apollo assign httpLink to authLink.concat after promise is fulfilled ??
Thanks for posting, all - I’d be happy to help out. @golsah can you share some sample code so the community can see what you see?
@rosnk the Apollo Link docs might be able to answer your questions about how the link chain functions. To my knowledge, Storage#getItem is a synchronous operation. The return value of setContext is an instance of ApolloLink, which is not an async function.
I hope that helps move the conversation forward, thanks again!
Sure! I am creating a React SignUp form based on my GraphQL API. The API perfectly works but the React App doesn’t. There is “Unexpected token” error in my signup.js file, which can be seen below.