Search code examples
javascriptreactjsapollo

Awaiting function inside ApolloLink


I have this part of my code that runs every time I perform an apollo API call. My goal is to check if the user is authenticated and has the latest refreshed token before making the API call. My issue is that I am unable to await the commented out line because the function is not async

const authenticationLink = new ApolloLink((operation, forward) => {

  // const currentSession = await Auth.currentSession();
  // setAccessToken(currentSession.signInUserSession.idToken.jwtToken)

  if (typeof token === "string") {
    operation.setContext(() => ({
      headers: {
        Authorization: token
      }
    }));
  }

  return forward(operation);
});


const standardLink = ApolloLink.from([
  authenticationLink,
  httpLink
]);

If I make authenticationLink async do I need to alter the other code below to await it or can it stay the same?


Solution

  • await is used with async. (More details here)

    Replace

    const authenticationLink = new ApolloLink((operation, forward) => {
    

    To

    const authenticationLink = new ApolloLink(async (operation, forward) => {