Skip to main content

AppSync SDK

Github: aws-mobile-appsync-sdk-js

Install Dependencies

Yarn

yarn add aws-appsync

or

NPM

npm install --save aws-appsync

Configure Apollo

import AWSAppSyncClient from "aws-appsync";
import AppSyncConfig from "./aws-exports";
import { ApolloProvider } from "react-apollo";
import { Rehydrated } from "aws-appsync-react"; // this needs to also be installed when working with React

import App from "./App";

const client = new AWSAppSyncClient({
url: AppSyncConfig.aws_appsync_graphqlEndpoint,
region: AppSyncConfig.aws_appsync_region,
auth: {
type: AppSyncConfig.aws_appsync_authenticationType,
apiKey: AppSyncConfig.aws_appsync_apiKey,
// jwtToken: async () => token, // Required when you use Cognito UserPools OR OpenID Connect. Token object is obtained previously
// credentials: async () => credentials, // Required when you use IAM-based auth.
},
});

const WithProvider = () => (
<ApolloProvider client={client}>
<Rehydrated>
<App />
</Rehydrated>
</ApolloProvider>
);

export default WithProvider;

Call API

import gql from "graphql-tag";
import { graphql } from "react-apollo";

const listPosts = gql`
query listPosts {
listPosts {
items {
id
name
}
}
}
`;
class App extends Component {
render() {
return (
<div>
{this.props.posts.map((post, index) => (
<h2 key={post.id ? post.id : index}>{post.name}</h2>
))}
</div>
);
}
}

export default graphql(listPosts, {
options: {
fetchPolicy: "cache-and-network",
},
props: (props) => ({
posts: props.data.listPosts ? props.data.listPosts.items : [],
}),
})(App);