Search code examples
javascriptreact-nativeapolloreact-apollo

creatHttpLink from asyncStorage, Apollo, React Native


"react-apollo": "3.1.5",

"react-native": "https://github.com/expo/react-native/archive/sdk-38.0.2.tar.gz"

"expo": "38.0.0"

I am trying to get my url from local asyncStorage (mainly for the reason than my url is picked from two urls after login and assigned to asyncStorage). Here is what I already tried but all the time I am getting undefined data

const asyncHttpLink = setContext(async (_, {headers, ...context}) => {
  const url = await getUrlFromAsyncStorage();
  return createHttpLink({
    uri: url ? url : '',
    ...context,
  });
});

then I assign it into my Appolo

const client = new ApolloClient({
  ... other property as cache, type etc. ...
  link: ApolloLink.from([
    ... other links ...
    asyncHttpLink,
  ]),
});

on response I get all the properties except data which are always undefined

[
  "variables",
  "refetch",
  ... other 7 ...,
  "error",
  "called",
  "data", <== always undefined
  "client",
]

but if I use standard createHttpLink, all starts working just fine

const httpLink = createHttpLink({
  uri: desiredUrl,
});

anybody has been chasing the same situation?


Solution

  • I found the solution:

    const customFetch = async (_: string, options: RequestInit) => {
      const url = await getUrlFromAsyncStorage();
      return url ? fetch(url, options) : fetch('');
    };
    
    const asyncHttpLink = createHttpLink({
      fetch: customFetch,
    });