Apollo Client setup template in React and React Native
Tue Jul 19 2022 13:46:17 GMT+0000 (Coordinated Universal Time)
Saved by
@jadorkor
#javascript
#react.js
import { ApolloClient, InMemoryCache, createHttpLink } from "@apollo/client";
const httpLink = createHttpLink({
uri: <insert uri here>,
});
//Without authentication
const createApolloClient = () => {
return new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
});
}
/* With authentication using setContext. <authentication_token> can also be a function or method returning an authentication token */
import {setContext} from "@apollo/client/link/context";
const createApolloClient = (<authentication_token>) => {
const authLink = setContext(async (_, { headers }) => {
try {
const accessToken = <authentication_token>;
return {
headers: {
...headers,
authorization: accessToken ? `Bearer ${accessToken}` : "",
},
};
} catch (e) {
console.log(e);
return {
headers,
};
}
});
return new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
};
export default createApolloClient;
content_copyCOPY
Comments