ApolloClient,
InMemoryCache,
makeVar,
createHttpLink,
split,
} from "@apollo/client";
import { setContext } from "@apollo/client/link/context";
import { WebSocketLink } from "@apollo/client/link/ws";
import { getMainDefinition } from "@apollo/client/utilities";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { LOCALSTORAGE_TOKEN } from "./constants";
const getData = async () => {
try {
const value = await AsyncStorage.getItem("@storage_Key");
if (value !== null) {
console.log("there is no value");
}
} catch (e) {
console.log(e);
}
};
const token = getData();
export const isLoggedInVar = makeVar(Boolean(token));
export const authTokenVar = makeVar(token);
const wsLink = new WebSocketLink({
uri: "wss://example.eastus.cloudapp.azure.com/graphql",
options: {
reconnect: true,
connectionParams: {
"x-jwt": authTokenVar() || "",
},
},
});
const httpLink = createHttpLink({
uri: "https://example.eastus.cloudapp.azure.com/graphql",
});
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
"x-jwt": authTokenVar() || "",
},
};
});
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === "OperationDefinition" &&
definition.operation === "subscription"
);
},
wsLink,
authLink.concat(httpLink)
);
export const client = new ApolloClient({
link: splitLink,
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
isLoggedIn: {
read() {
return isLoggedInVar();
},
},
token: {
read() {
return token;
},
},
},
},
},
}),
});
Last active
May 2, 2021 11:31
-
-
Save GwamakaCharles/52680fd2efe144cb3fc3d7d5f84f0120 to your computer and use it in GitHub Desktop.
React native apollo setup
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment