Connect to existing AWS AppSync API from a React Application

Have an existing API within AWS AppSync and need to connect it from a React web application? If you are not completely new to GraphQL you should know that the most popular GraphQL client is Apollo.

There are many different way to connect to AWS AppSync with React, using different packages. Some required more packages/dependencies.

aws_appsync

1. Use Apollo client

The latest version @apollo/client can handle AWS AppSync’s query and mutation just fine with simple setup and also support React hook out of the box. Per their official doc, they will only support useQuery for query and useMutation for mutation hooks in their future release. Component based query and mutation will still work but will not be supported. However, for subscription, @apollo/client and AWS AppSync API won’t work without complex setup because AppSync’s subscriptions use MQTT as the transport layer, but @apollo/client support WebSockets.

If you are using React with version that support hook, and you don’t have the need for subscription, this option will work very well.

  1. Install required package
    yarn add @apollo/client aws-appsync-auth-link graphql
  2. Create client.js with following setup. aws-exports is the config download from your AWS AppSync API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import {
ApolloClient, ApolloLink, InMemoryCache, createHttpLink,
} from '@apollo/client';
import { createAuthLink } from 'aws-appsync-auth-link';
import AppSyncConfig from './aws-exports';

const url = AppSyncConfig.aws_appsync_graphqlEndpoint;
const region = AppSyncConfig.aws_project_region;
const auth = {
type: AppSyncConfig.aws_appsync_authenticationType,
apiKey: AppSyncConfig.aws_appsync_apiKey,
};
const link = ApolloLink.from([
// @ts-ignore
createAuthLink({ url, region, auth }),
// @ts-ignore
createHttpLink({ uri: url }),
]);
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});

export default client;
  1. In your index.js add below code to Apollo client accessible.
    ApolloProvider will make your AppSync client accessable any child of the entry point component whic is App in this example.
1
2
3
4
5
6
import { ApolloProvider } from '@apollo/client';
import client from './graphQL/client';

<ApolloProvider client={client}>
<App />
</ApolloProvider>

Example of making a mutation call:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import {
useMutation,
gql
} from '@apollo/client';

const createTodo = gql`
mutation CreateTodo(
item: String!
) {
createUpdateMonitor(input: {
item: item
}) {
item
}
}
`;
const [createTodoMutation] = useMutation(createTodo);

const handleCreateTodoClick = () => {
const todo = {
item: 'visit qualityology.com'
}
createTodoMutation({
variables: todo,
})
.then((res) => console.log('Todo created successfully'))
.catch((err) => {
console.log('Error occurred');
console.log(err);
});
};

2. Use AWS AppSync JavaScript SDK

This SDK can be used with apollo-client and it is the offical SDK provided by AWS Labs. It support offline feature and also work with class components. Your index.js will need to be setup with the following code. You will need to download aws-exports.js from your AWS AppSync API and install react-apollo aws-appsync-react for this setup. ``aws-exports.js` contains the GraphQL endpoint url and your AWS AppSync API region, auth type info.

new AWSAppSyncClient will create a new AppSync client and store it in the client variable.
ApolloProvider will make your AppSync client accessible any child of the entry point component whic is App in this example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import AWSAppSyncClient from 'aws-appsync'
import React from 'react';
import ReactDOM from 'react-dom';
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.graphqlEndpoint,
region: AppSyncConfig.region,
auth: {
type: AppSyncConfig.authenticationType,
apiKey: AppSyncConfig.apiKey,
// jwtToken: async () => token, // Required when you use Cognito UserPools OR OpenID Connect. token object is obtained previously
}
})

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

ReactDOM.render(<WithProvider />, document.getElementById('root'));

Rehydrate will make sure application cache has been read and is ready to use before rendering the app. If app is not ready, it will show the default loading text. If you want to confured the display text, you can call the render function as below.

1
2
3
4
5
<Rehydrated
render={({ rehydrated }) => (
rehydrated ? <App /> : <div>Fancy loading function here!</div>
)}
/>

This method didn’t work with out test application because it always show loading so it is not recommended to use unless you want to try it with a good reason. You can get more configuration from the project page here.

3. Use AWS Amplify

This is the easiest and with complete support of query, mutation, and subscription for AWS AppSync API. You will need your AWS AppSync API ID and the config export for this method. It can be found in AWS console.

  1. Install AWS Amplify cli.

    1
    npm install -g @aws-amplify/cli

    The cli is needed for importing API

  2. Navigate to your React project root folder.

    1
    amplify init
  3. Add the codegen category to your React project.

    1
    amplify add codegen --apiId YOUR_API_ID_HERE
  4. Generate client code.

    1
    amplify codegen

    Follow the steps in your terminal.

  5. Add aws-amplify

    1
    npm install aws-amplify

    or use yarn

    1
    yarn add aws-amplify
  6. Add below code to your React application root index.js

    1
    2
    3
    4
    5
    6
    7
    8
    // some imports here
    import { Amplify } from 'aws-amplify';
    import amplifyConfig from './aws-exports';
    // after all the imports

    Amplify.configure(amplifyConfig);

    // the rest of the code, ReactDOM etc.

    Example of how the function used to call mutation look like:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    import { API, graphqlOperation } from 'aws-amplify';
    import { createTodo } from '/graphql/mutations';

    const todo = {
    item: 'visit qualityology.com'
    }
    const update = await API.graphql(
    graphqlOperation(
    createTodo,
    {
    input: todo,
    },
    ),
    )
    .then((res) => res)
    .catch((error) => console.log('error, creating user', error));
    console.log('update', update);
Install Docker and Docker Compose On Raspberry Pi 29 Code Snippets for WordPress Users

Comments