{"id":13446093,"url":"https://github.com/dabit3/aws-amplify-workshop-react-native","last_synced_at":"2025-11-17T15:26:48.497Z","repository":{"id":53803022,"uuid":"146994654","full_name":"dabit3/aws-amplify-workshop-react-native","owner":"dabit3","description":"Building Cloud-enabled Mobile Applications with React Native \u0026 AWS Amplify","archived":false,"fork":false,"pushed_at":"2021-03-12T15:26:37.000Z","size":821,"stargazers_count":140,"open_issues_count":3,"forks_count":33,"subscribers_count":8,"default_branch":"master","last_synced_at":"2025-04-07T01:12:10.934Z","etag":null,"topics":["amplify","appsync","aws","aws-amplify","aws-appsync","react","react-native","serverless"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dabit3.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-09-01T11:59:41.000Z","updated_at":"2024-07-04T04:42:08.000Z","dependencies_parsed_at":"2022-08-22T04:40:53.048Z","dependency_job_id":null,"html_url":"https://github.com/dabit3/aws-amplify-workshop-react-native","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabit3%2Faws-amplify-workshop-react-native","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabit3%2Faws-amplify-workshop-react-native/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabit3%2Faws-amplify-workshop-react-native/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabit3%2Faws-amplify-workshop-react-native/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dabit3","download_url":"https://codeload.github.com/dabit3/aws-amplify-workshop-react-native/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249091482,"owners_count":21211354,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["amplify","appsync","aws","aws-amplify","aws-appsync","react","react-native","serverless"],"created_at":"2024-07-31T05:00:45.369Z","updated_at":"2025-11-17T15:26:43.467Z","avatar_url":"https://github.com/dabit3.png","language":"JavaScript","funding_links":[],"categories":["Development and CI/CD","Workshops"],"sub_categories":[],"readme":"# Building Mobile Applications with React Native \u0026 AWS Amplify\n\nIn this workshop we'll learn how to build cloud-enabled mobile applications with React Native \u0026 [AWS Amplify](https://aws-amplify.github.io/).\n\n![Amplify React Native Workshop](header.jpg)\n\n### Topics we'll be covering:\n\n- [Authentication](https://github.com/dabit3/aws-amplify-workshop-react-native#adding-authentication)\n- [GraphQL API with AWS AppSync](https://github.com/dabit3/aws-amplify-workshop-react-native#adding-a-graphql-api-with-aws-appsync)\n- [Serverless Functions](https://github.com/dabit3/aws-amplify-workshop-react-native#adding-a-serverless-function)\n- [REST API with a Lambda Function](https://github.com/dabit3/aws-amplify-workshop-react-native#adding-a-rest-api)\n- [Analytics](https://github.com/dabit3/aws-amplify-workshop-react-native#adding-analytics)\n- [Adding Storage with Amazon S3](https://github.com/dabit3/aws-amplify-workshop-react-native#working-with-storage)\n- [Multiple Serverless Environments](https://github.com/dabit3/aws-amplify-workshop-react-native#multiple-serverless-environments)\n- [Removing / Deleting Services](https://github.com/dabit3/aws-amplify-workshop-react-native#removing-services)\n\n\u003c!-- ## Redeeming the AWS Credit   \n\n1. Visit the [AWS Console](https://console.aws.amazon.com/console).\n2. In the top right corner, click on __My Account__.\n![](dashboard1.jpg)\n3. In the left menu, click __Credits__.\n![](dashboard2.jpg) --\u003e\n\n## Getting Started - Creating the React Native Application\n\nTo get started, we first need to create a new React Native project \u0026 change into the new directory using either the [React Native CLI](https://facebook.github.io/react-native/docs/getting-started.html) (See __Building Projects With Native Code__ in the documentation) or [Expo CLI](https://facebook.github.io/react-native/docs/getting-started).\n\nWe can use the React Native CLI or Expo to create a new app:\n\n### If you're using the React Native CLI (you're not using Expo)\n\nChange into the app directory \u0026 install the dependencies\n\n```bash\n$ npx react-native init RNAmplify\n\n$ cd RNAmplify\n\n$ npm install --save aws-amplify aws-amplify-react-native uuid amazon-cognito-identity-js @react-native-community/netinfo\n\n# or\n\n$ yarn add aws-amplify aws-amplify-react-native uuid amazon-cognito-identity-js @react-native-community/netinfo\n```\n\nNext, for iOS you need to install the pods:\n\n```sh\n$ cd ios\n\n$ pod install --repo-update\n\n$ cd ..\n```\n\n### If you are using Expo\n\n```bash\n$ npx expo init RNAmplify\n\n\u003e Choose a template: blank\n\n$ cd RNAmplify\n\n$ npm install --save aws-amplify aws-amplify-react-native uuid @react-native-community/netinfo\n\n# or\n\n$ yarn add aws-amplify aws-amplify-react-native uuid\n```\n\n### Running the app\n\nNext, run the app:\n\n```sh\n$ npx react-native run-ios\n\n# or if running android\n\n$ npx react-native run-android\n\n# or, if using expo\n\n$ expo start\n```\n\n## Installing the CLI \u0026 Initializing a new AWS Amplify Project\n\n### Installing the CLI\n\nNext, we'll install the AWS Amplify CLI:\n\n```bash\n$ npm install -g @aws-amplify/cli\n```\n\nNow we need to configure the CLI with our credentials:\n\n```js\n$ amplify configure\n```\n\n\u003e If you'd like to see a video walkthrough of this configuration process, click [here](https://www.youtube.com/watch?v=fWbM5DLh25U).\n\nHere we'll walk through the `amplify configure` setup. Once you've signed in to the AWS console, continue:\n- Specify the AWS Region: __your preferred region__\n- Specify the username of the new IAM user: __amplify-workshop-user__\n\u003e In the AWS Console, click __Next: Permissions__, __Next: Tags__, __Next: Review__, \u0026 __Create User__ to create the new IAM user. Then, return to the command line \u0026 press Enter.\n- Enter the access key of the newly created user:   \n  accessKeyId: __(\u003cYOUR_ACCESS_KEY_ID\u003e)__   \n  secretAccessKey:  __(\u003cYOUR_SECRET_ACCESS_KEY\u003e)__\n- Profile Name: __amplify-workshop-user__\n\n### Initializing A New AWS Amplify Project\n\n\u003e Make sure to initialize this Amplify project in the root of your new React Native application\n\n```bash\n$ amplify init\n```\n\n- Enter a name for the project: __RNAmplify__\n- Enter a name for the environment: __dev__\n- Choose your default editor: __Visual Studio Code (or your favorite editor)__   \n- Please choose the type of app that you're building __javascript__   \n- What javascript framework are you using __react-native__   \n- Source Directory Path: __/__   \n- Distribution Directory Path: __/__\n- Build Command: __npm run-script build__   \n- Start Command: __npm run-script start__   \n- Select the authentication method you want to use: __AWS profile__\n- Please choose the profile you want to use: __amplify-workshop-user__\n\nNow, the AWS Amplify CLI has iniatilized a new project \u0026 you will see a couple of new files \u0026 folders: __amplify__ \u0026 __aws-exports.js__. These files hold your project configuration.\n\n### Configuring the React Native application\n\nThe next thing we need to do is to configure our React Native application to be aware of our new AWS Amplify project. We can do this by referencing the auto-generated __aws-exports.js__ file that is now in our root folder.\n\n### If you are using the React Native CLI (not using Expo)\n\nTo configure the app, open __index.js__ and add the following code below the last import:\n\n```js\n// index.js\nimport Amplify from 'aws-amplify'\nimport config from './aws-exports'\nAmplify.configure(config)\n```\n\nNow, our app is ready to start using our AWS services.\n\n### If you are using the Expo (not using the React Native CLI)\n\nTo configure the app, open __App.js__ and add the following code below the last import:\n\n```js\n// App.js\nimport Amplify from 'aws-amplify'\nimport config from './aws-exports'\nAmplify.configure(config)\n```\n\nNow, our app is ready to start using our AWS services.\n\n## Adding Authentication\n\nTo add authentication, we can use the following command:\n\n```sh\n$ amplify add auth\n```\n\n- Do you want to use default authentication and security configuration? __Default configuration__   \n- How do you want users to be able to sign in when using your Cognito User Pool? __Username__ (keep default) \n- Do you want to configure advanced settings? __No__\n\nNow, we'll run the push command and the cloud resources will be created in our AWS account.\n\n```bash\n$ amplify push\n```\n\nTo view the AWS services any time after their creation, run the following command:\n\n```sh\n$ amplify console\n```\n\n### Using the withAuthenticator component\n\nTo add authentication, we'll go into __App.js__ and first import the `withAuthenticator` HOC (Higher Order Component) from `aws-amplify-react`:\n\n```js\n// App.js\nimport { withAuthenticator } from 'aws-amplify-react-native'\n```\n\nNext, we'll wrap our default export (the App component) with the `withAuthenticator` HOC:\n\n```js\nexport default withAuthenticator(App, {\n  includeGreetings: true\n})\n```\n\nNow, we can run the app and see that an Authentication flow has been added in front of our App component. This flow gives users the ability to sign up \u0026 sign in.\n\nTo refresh, you can use one of the following commands:\n\n```sh\n# iOS Simulator\nCMD + d # Opens debug menu\nCMD + r # Reloads the app\n\n# Android Emulator\nCTRL + m # Opens debug menu\nrr # Reloads the app\n```\n\n### Accessing User Data\n\nWe can access the user's info now that they are signed in by calling `Auth.currentAuthenticatedUser()`.\n\n```js\n// App.js\nimport React from 'react';\nimport {\n  SafeAreaView,\n  StyleSheet,\n  Text,\n} from 'react-native';\n\nimport { withAuthenticator } from 'aws-amplify-react-native'\n\nimport { Auth } from 'aws-amplify' \n\nclass App extends React.Component {\n  async componentDidMount() {\n    const user = await Auth.currentAuthenticatedUser()\n    console.log('user:', user)\n  }\n  render() {\n    return (\n      \u003cSafeAreaView style={styles.container}\u003e\n        \u003cText style={styles.title}\u003eHello World\u003c/Text\u003e\n      \u003c/SafeAreaView\u003e\n    )\n  }\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    justifyContent: 'center',\n    alignItems: 'center'\n  },\n  title: {\n    fontSize: 28\n  }\n})\n\nexport default withAuthenticator(App, {\n  includeGreetings: true\n})\n```\n\n### Signing out with a custom Sign Out button\n\nWe can also sign the user out using the `Auth` class \u0026 calling `Auth.signOut()`. This function returns a promise that is fulfilled after the user session has been ended \u0026 AsyncStorage is updated.\n\nBecause `withAuthenticator` holds all of the state within the actual component, we must have a way to rerender the actual `withAuthenticator` component by forcing React to rerender the parent component.\n\nTo do so, let's make a few updates:\n\n```js\n// App.js\nimport React from 'react';\nimport {\n  SafeAreaView,\n  StyleSheet,\n  Text,\n} from 'react-native';\n\nimport { withAuthenticator } from 'aws-amplify-react-native'\n\nimport { Auth } from 'aws-amplify' \n\nclass App extends React.Component {\n  async componentDidMount() {\n    const user = await Auth.currentAuthenticatedUser()\n    console.log('user:', user)\n  }\n  signOut = () =\u003e {\n    Auth.signOut()\n      .then(() =\u003e this.props.onStateChange('signedOut'))\n      .catch(err =\u003e console.log('err: ', err))\n  }\n  render() {\n    return (\n      \u003cSafeAreaView style={styles.container}\u003e\n        \u003cText style={styles.title}\u003eHello World\u003c/Text\u003e\n        \u003cText onPress={this.signOut}\u003eSign Out\u003c/Text\u003e\n      \u003c/SafeAreaView\u003e\n    )\n  }\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    justifyContent: 'center',\n    alignItems: 'center'\n  },\n  title: {\n    fontSize: 28\n  }\n})\n\nexport default withAuthenticator(App);\n\n```\n\n### Custom authentication strategies\n\nTo view a final solution for a custom authentication strategy, check out the __AWS Amplify React Native Auth Starter__ [here](https://github.com/aws-samples/aws-amplify-auth-starters/tree/react-native#aws-amplify-react-native-auth-starter).\n\n\u003e This section is an overview and is considered an advanced part of the workshop. If you are not comfortable writing a custom authentication flow, I would read through this section and use it as a reference in the future. If you'd like to jump to the next section, click [here](https://github.com/dabit3/aws-amplify-workshop-react-native#adding-a-graphql-api-with-aws-appsync).\n\nThe `withAuthenticator` component is a really easy way to get up and running with authentication, but in a real-world application we probably want more control over how our form looks \u0026 functions.\n\nLet's look at how we might create our own authentication flow.\n\nTo get started, we would probably want to create input fields that would hold user input data in the state. For instance when signing up a new user, we would probably need 3 user inputs to capture the user's username, email, \u0026 password.\n\nTo do this, we could create some initial state for these values \u0026 create an event handler that we could attach to the form inputs:\n\n```js\n// initial state\nstate = {\n  username: '', password: '', email: ''\n}\n\n// event handler\nonChangeText = (key, value) =\u003e {\n  this.setState({ [key]: value })\n}\n\n// example of usage with TextInput\n\u003cTextInput\n  placeholder='username'\n  value={this.state.username}\n  style={{ width: 300, height: 50, margin: 5, backgroundColor: \"#ddd\" }}\n  onChangeText={v =\u003e this.onChange('username', v)}\n/\u003e\n```\n\nWe'd also need to have a method that signed up \u0026 signed in users. We can us the Auth class to do thi. The Auth class has over 30 methods including things like `signUp`, `signIn`, `confirmSignUp`, `confirmSignIn`, \u0026 `forgotPassword`. Thes functions return a promise so they need to be handled asynchronously.\n\n```js\n// import the Auth component\nimport { Auth } from 'aws-amplify'\n\n// Class method to sign up a user\nsignUp = async() =\u003e {\n  const { username, password, email } = this.state\n  try {\n    await Auth.signUp({ username, password, attributes: { email }})\n  } catch (err) {\n    console.log('error signing up user...', err)\n  }\n}\n```\n\n## Adding a GraphQL API with AWS AppSync\n\nTo add a GraphQL API, we can use the following command:\n\n```sh\n$ amplify add api\n```\n\nAnswer the following questions\n\n- Please select from one of the above mentioned services __GraphQL__   \n- Provide API name: __RestaurantAPI__   \n- Choose the default authorization type for the API __API key__   \n- Enter a description for the API key __public__\n- After how many days from now the API key should expire __365__\n- Do you want to configure advanced settings for the GraphQL API __No__\n- Do you have an annotated GraphQL schema? __N__   \n- Choose a schema template: __Single object with fields (e.g. “Todo” with ID, name, description)__   \n- Do you want to edit the schema now? (Y/n) __Y__   \n\n\u003e When prompted, update the schema to the following:   \n\n```graphql\ntype Restaurant @model {\n  id: ID!\n  clientId: String\n  name: String!\n  description: String!\n  city: String!\n}\n```\n\nNext, deploy the API:\n\n```sh\namplify push\n\n? Are you sure you want to continue? Yes\n? Do you want to generate code for your newly created GraphQL API: Yes\n? Choose the code generation language target: javascript\n? Enter the file name pattern of graphql queries, mutations and subscriptions: ./graphql/**/*.js\n? Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions: Yes\n? Enter maximum statement depth [increase from default if your schema is deeply nested] (2)\n```\n\n### Optional - To mock and test the API locally, you can run the mock command:\n\n```bash\n$ amplify mock api\n```\n\nThis should start an AppSync Mock endpoint:\n\n```\nAppSync Mock endpoint is running at http://10.219.99.136:20002\n```\n\nOpen the endpoint in the browser to use the GraphiQL Editor.\n\nFrom here, we can now test the API.\n\n### Adding mutations from within the GraphiQL Editor.\n\nIn the GraphiQL editor, execute the following mutation to create a new restaurant in the API:\n\n```graphql\nmutation createRestaurant {\n  createRestaurant(input: {\n    name: \"Nobu\"\n    description: \"Great Sushi\"\n    city: \"New York\"\n  }) {\n    id name description city\n  }\n}\n```\n\nNow, let's query for the restaurant:\n\n```graphql\nquery listRestaurants {\n  listRestaurants {\n    items {\n      id\n      name\n      description\n      city\n    }\n  }\n}\n```\n\nWe can even add search / filter capabilities when querying:\n\n```graphql\nquery searchRestaurants {\n  listRestaurants(filter: {\n    city: {\n      contains: \"New York\"\n    }\n  }) {\n    items {\n      id\n      name\n      description\n      city\n    }\n  }\n}\n```\n\nOr, get an individual restaurant by ID:\n\n```graphql\nquery getRestaurant {\n  getRestaurant(id: \"RESTAURANT_ID\") {\n    name\n    description\n    city\n  }\n}\n```\n\n### Interacting with the GraphQL API from our client application - Querying for data\n\nNow that the GraphQL API is created we can begin interacting with it!\n\nThe first thing we'll do is perform a query to fetch data from our API.\n\nTo do so, we need to define the query, execute the query, store the data in our state, then list the items in our UI.\n\n```js\nimport React from 'react';\nimport {\n  SafeAreaView,\n  View,\n  StyleSheet,\n  Text,\n} from 'react-native';\n\n// imports from Amplify library\nimport { withAuthenticator } from 'aws-amplify-react-native'\nimport { API, graphqlOperation } from 'aws-amplify'\n\n// import the GraphQL query\nimport { listRestaurants } from './graphql/queries'\n\nclass App extends React.Component {\n  // define some state to hold the data returned from the API\n  state = {\n    restaurants: []\n  }\n  // execute the query in componentDidMount\n  async componentDidMount() {\n    try {\n      const restaurantData = await API.graphql(graphqlOperation(listRestaurants))\n      console.log('restaurantData:', restaurantData)\n      this.setState({\n        restaurants: restaurantData.data.listRestaurants.items\n      })\n    } catch (err) {\n      console.log('error fetching restaurants...', err)\n    }\n  }\n  render() {\n    return (\n      \u003cSafeAreaView style={styles.container}\u003e\n        {\n          this.state.restaurants.map((restaurant, index) =\u003e (\n            \u003cView key={index} style={styles.item}\u003e\n              \u003cText style={styles.name}\u003e{restaurant.name}\u003c/Text\u003e\n              \u003cText style={styles.description}\u003e{restaurant.description}\u003c/Text\u003e\n              \u003cText style={styles.city}\u003e{restaurant.city}\u003c/Text\u003e\n            \u003c/View\u003e\n          ))\n        }\n      \u003c/SafeAreaView\u003e\n    )\n  }\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    justifyContent: 'center',\n  },\n  item: { padding: 10 },\n  name: { fontSize: 20 },\n  description: { fontWeight: '600', marginTop: 4, color: 'rgba(0, 0, 0, .5)' },\n  city: { marginTop: 4 }\n})\n\nexport default withAuthenticator(App, { includeGreetings: true });\n```\n\n## Performing mutations\n\n Now, let's look at how we can create mutations. The mutation we will be working with is `createRestaurant`.\n\n```js\n// App.js\nimport React from 'react';\nimport {\n  SafeAreaView,\n  View,\n  StyleSheet,\n  Text,\n  TextInput,\n  Button\n} from 'react-native';\n\n// imports from Amplify library\nimport { withAuthenticator } from 'aws-amplify-react-native'\nimport { API, graphqlOperation } from 'aws-amplify'\n\n// import the GraphQL query\nimport { listRestaurants } from './graphql/queries'\n// import the GraphQL mutation\nimport { createRestaurant } from './graphql/mutations'\n\n// create client ID\nimport { v4 as uuid } from 'uuid'\nconst CLIENTID = uuid()\n\nclass App extends React.Component {\n  // add additional state to hold form state as well as restaurant data returned from the API\n  state = {\n    name: '', description: '', city: '', restaurants: []\n  }\n  // execute the query in componentDidMount\n  async componentDidMount() {\n    try {\n      const restaurantData = await API.graphql(graphqlOperation(listRestaurants))\n      console.log('restaurantData:', restaurantData)\n      this.setState({\n        restaurants: restaurantData.data.listRestaurants.items\n      })\n    } catch (err) {\n      console.log('error fetching restaurants...', err)\n    }\n  }\n  // this method calls the API and creates the mutation\n  createRestaurant = async() =\u003e {\n    const { name, description, city  } = this.state\n    // store the restaurant data in a variable\n    const restaurant = {\n      name, description, city, clientId: CLIENTID\n    }\n    // perform an optimistic response to update the UI immediately\n    const restaurants = [...this.state.restaurants, restaurant]\n    this.setState({\n      restaurants,\n      name: '', description: '', city: ''\n      })\n    try {\n      // make the API call\n      await API.graphql(graphqlOperation(createRestaurant, {\n        input: restaurant\n      }))\n      console.log('item created!')\n    } catch (err) {\n      console.log('error creating restaurant...', err)\n    }\n  }\n  // change form state then user types into input\n  onChange = (key, value) =\u003e {\n    this.setState({ [key]: value })\n  }\n  render() {\n    return (\n      \u003cSafeAreaView style={styles.container}\u003e\n        \u003cTextInput\n          style={{ height: 50, margin: 5, backgroundColor: \"#ddd\" }}\n          onChangeText={v =\u003e this.onChange('name', v)}\n          value={this.state.name} placeholder='name'\n        /\u003e\n        \u003cTextInput\n          style={{ height: 50, margin: 5, backgroundColor: \"#ddd\" }}\n          onChangeText={v =\u003e this.onChange('description', v)}\n          value={this.state.description} placeholder='description'\n        /\u003e\n        \u003cTextInput\n          style={{ height: 50, margin: 5, backgroundColor: \"#ddd\" }}\n          onChangeText={v =\u003e this.onChange('city', v)}\n          value={this.state.city} placeholder='city'\n        /\u003e\n        \u003cButton onPress={this.createRestaurant} title='Create Restaurant' /\u003e\n        {\n          this.state.restaurants.map((restaurant, index) =\u003e (\n            \u003cView key={index} style={styles.item}\u003e\n              \u003cText style={styles.name}\u003e{restaurant.name}\u003c/Text\u003e\n              \u003cText style={styles.description}\u003e{restaurant.description}\u003c/Text\u003e\n              \u003cText style={styles.city}\u003e{restaurant.city}\u003c/Text\u003e\n            \u003c/View\u003e\n          ))\n        }\n      \u003c/SafeAreaView\u003e\n    )\n  }\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    justifyContent: 'center',\n  },\n  item: { padding: 10 },\n  name: { fontSize: 20 },\n  description: { fontWeight: '600', marginTop: 4, color: 'rgba(0, 0, 0, .5)' },\n  city: { marginTop: 4 }\n})\n\nexport default withAuthenticator(App, { includeGreetings: true });\n```\n\n## Challenge\n\nRecreate this functionality in Hooks\n\n\u003e For direction, check out the tutorial [here](https://medium.com/open-graphql/react-hooks-for-graphql-3fa8ebdd6c62)\n\n\u003e For the solution to this challenge, view the [hooks](graphqlHooks.js) file.\n\n## Adding a Serverless Function\n\n### Adding a basic Lambda Function\n\nTo add a serverless function, we can run the following command:\n\n```sh\n$ amplify add function\n\n? Select which capability you want to add: Lambda function\n? Provide an AWS Lambda function nam: basiclambda\n? Choose the runtime that you want to use: NodeJS\n? Choose the function template that you want to use: Hello World\n? Do you want to configure advanced settings? N\n? Do you want to edit the local lambda function now? Y\n```\n\n\u003e This should open the function package located at __amplify/backend/function/basiclambda/src/index.js__.\n\nEdit the function to look like this, \u0026 then save the file.\n\n```js\nexports.handler = async (event, contex) =\u003e {\n  console.log('event: ', event)\n  const body = {\n    message: \"Hello world!\"\n  }\n  const response = {\n    statusCode: 200,\n    body\n  }\n  return response\n}\n```\n\nNext, we can test this out by running:\n\n```sh\n$ amplify mock function basiclambda\n\n? Provide the path to the event JSON object: src/event.json\n```\n\nYou'll notice the following output from your terminal:\n\n```sh\nEnsuring latest function changes are built...\nStarting execution...\nevent:  { key1: 'value1', key2: 'value2', key3: 'value3' }\nResult:\n{\n  \"statusCode\": 200,\n  \"body\": {\n    \"message\": \"Hello world!\"\n  }\n}\nFinished execution.\n```\n\n_Where is the event data coming from? It is coming from the values located in event.json in the function folder (__amplify/backend/function/basiclambda/src/event.json__). If you update the values here, you can simulate data coming arguments the event._\n\nFeel free to test out the function by updating `event.json` with data of your own.\n\n### Adding a function running an express server and invoking it from an API call (http)\n\nNext, we'll build a function that will be running an [Express](https://expressjs.com/) server inside of it.\n\nThis new function will fetch data from a cryptocurrency API \u0026 return the values in the response.\n\nTo get started, we'll create a new function:\n\n```sh\n$ amplify add function\n\n? Select which capability you want to add: Lambda function\n? Provide an AWS Lambda function name: cryptofunction\n? Choose the runtime that you want to use: NodeJS\n? Choose the function template that you want to use: Serverless ExpressJS\n? Do you want to configure advanced settings? No\n? Do you want to edit the local lambda function now? Y\n```\n\nThis should open the function package located at __amplify/backend/function/cryptofunction/src/index.js__. You'll notice in this file, that the event is being proxied into an express server:\n\n```js\nexports.handler = (event, context) =\u003e {\n  console.log(`EVENT: ${JSON.stringify(event)}`);\n  awsServerlessExpress.proxy(server, event, context);\n};\n```\n\nInstead of updating the handler function itself, we'll instead update __amplify/backend/function/cryptofunction/src/app.js__ which has the actual server code we would like to be working with.\n\nHere, in __amplify/backend/function/cryptofunction/src/app.js__, we'll add the following code \u0026 save the file:\n\n```js\n// amplify/backend/function/cryptofunction/src/app.js\n\n// you should see this code already there 👇:\napp.use(function(req, res, next) {\n  res.header(\"Access-Control-Allow-Origin\", \"*\")\n  res.header(\"Access-Control-Allow-Headers\", \"Origin, X-Requested-With, Content-Type, Accept\")\n  next()\n});\n// below the above code, add the following code 👇 (be sure not to delete any other code from this file)\nconst axios = require('axios')\n\napp.get('/coins', function(req, res) {\n  let apiUrl = `https://api.coinlore.com/api/tickers?start=0\u0026limit=10`\n  \n  if (req \u0026\u0026 req.query) {\n    // here we are checking to see if there are any query parameters, and if so appending them to the request\n    const { start = 0, limit = 10 } = req.query\n    apiUrl = `https://api.coinlore.com/api/tickers/?start=${start}\u0026limit=${limit}`\n  }\n\n  axios.get(apiUrl)\n    .then(response =\u003e {\n      res.json({\n        coins: response.data.data\n      })\n    })\n    .catch(err =\u003e res.json({ error: err }))\n})\n```\n\nIn the above function we've used the __axios__ library to call another API. In order to use __axios__, we need be sure that it will be installed by updating the __package.json__ for the new function:\n\n```sh\n$ cd amplify/backend/function/cryptofunction/src\n\n$ npm install axios\n\n$ cd ../../../../../\n```\n\nNext, change back into the root directory.\n\n## Adding a REST API\n\nNow that we've created the cryptocurrency Lambda function let's add an API endpoint so we can invoke it via http.\n\nTo add the REST API, we can use the following command:\n\n```sh\n$ amplify add api\n\n? Please select from one of the above mentioned services: REST\n? Provide a friendly name for your resource that will be used to label this category in the project: cryptoapi   \n? Provide a path (e.g., /items): /coins   \n? Choose lambda source: Use a Lambda function already added in the current Amplify project   \n? Choose the Lambda function to invoke by this path: cryptofunction   \n? Restrict API access: Y\n? Who should have access? Authenticated users only\n? What kind of access do you want for Authenticated users: read/create/update/delete\n? Do you want to add another path? (y/N) N  \n```\n\nNow the resources have been created \u0026 configured \u0026 we can push them to our account: \n\n```bash\n$ amplify push\n\n? Are you sure you want to continue? Y\n```\n\n### Interacting with the new API\n\nNow that the API is created we can start sending requests to it \u0026 interacting with it.\n\nLet's request some data from the API:\n\n```js\n// App.js\nimport React from 'react'\nimport { View, Text, StyleSheet } from 'react-native'\nimport { API } from 'aws-amplify'\nimport { withAuthenticator } from 'aws-amplify-react-native'\n\nclass App extends React.Component {\n  state = {\n    coins: []\n  }\n  async componentDidMount() {\n    try {\n      // to get all coins, do not send in a query parameter\n      // const data = await API.get('cryptoapi', '/coins')\n      const data = await API.get('cryptoapi', '/coins?limit=5\u0026start=100')\n      console.log('data from Lambda REST API: ', data)\n      this.setState({ coins: data.coins })\n    } catch (err) {\n      console.log('error fetching data..', err)\n    }\n  }\n  render() {\n    return (\n      \u003cView\u003e\n        {\n          this.state.coins.map((c, i) =\u003e (\n            \u003cView key={i} style={styles.row}\u003e\n              \u003cText style={styles.name}\u003e{c.name}\u003c/Text\u003e\n              \u003cText\u003e{c.price_usd}\u003c/Text\u003e\n            \u003c/View\u003e\n          ))\n        }\n      \u003c/View\u003e\n    )\n  }\n}\n\nconst styles = StyleSheet.create({\n  row: { padding: 10 },\n  name: { fontSize: 20, marginBottom: 4 },\n})\n\nexport default withAuthenticator(App, { includeGreetings: true })\n```\n\n## Adding Analytics\n\nTo add analytics, we can use the following command:\n\n```sh\n$ amplify add analytics\n```\n\n\u003e Next, we'll be prompted for the following:\n\n- Provide your pinpoint resource name: __amplifyanalytics__   \n- Apps need authorization to send analytics events. Do you want to allow guest/unauthenticated users to send analytics events (recommended when getting started)? __Y__   \n\nTo deploy, run the `push` command:\n\n```sh\n$ amplify push\n```\n\n### Recording events\n\nNow that the service has been created we can now begin recording events.\n\nTo record analytics events, we need to import the `Analytics` class from Amplify \u0026 then call `Analytics.record`:\n\n```js\nimport { Analytics } from 'aws-amplify'\n\nstate = {username: ''}\n\nasync componentDidMount() {\n  try {\n    const user = await Auth.currentAuthenticatedUser()\n    this.setState({ username: user.username })\n  } catch (err) {\n    console.log('error getting user: ', err)\n  }\n}\n\nrecordEvent = () =\u003e {\n  Analytics.record({\n    name: 'My test event',\n    attributes: {\n      username: this.state.username\n    }\n  })\n}\n\n\u003cButton onPress={this.recordEvent} title='Record Event' /\u003e\n```\n\nTo view the analytics in the console, run the `console` command:\n\n```sh\n$ amplify console\n```\n\nIn the console, click on __Analytics__, then click on __View  in Pinpoint__. In the __Pinpoint__ console, click on __events__ and then enable filters.\n\n## Working with Storage\n\nTo add storage, we can use the following command:\n\n```sh\namplify add storage\n```\n\n\u003e Answer the following questions   \n\n- Please select from one of the below mentioned services __Content (Images, audio, video, etc.)__\n- Please provide a friendly name for your resource that will be used to label this category in the\n project: __rnworkshopstorage__\n- Please provide bucket name: __YOUR_UNIQUE_BUCKET_NAME__\n- Who should have access: __Auth users only__\n- What kind of access do you want for Authenticated users?\n\n```sh\n❯◉ create/update\n ◉ read\n ◉ delete\n```\n\n\n```sh\namplify push\n```\n\nNow, storage is configured \u0026 ready to use.\n\nWhat we've done above is created configured an Amazon S3 bucket that we can now start using for storing items.\n\nFor example, if we wanted to test it out we could store some text in a file like this:\n\n```js\nimport { Storage } from 'aws-amplify'\n\n// create function to work with Storage\naddToStorage = () =\u003e {\n  Storage.put('textfiles/mytext.txt', `Hello World`)\n    .then (result =\u003e {\n      console.log('result: ', result)\n    })\n    .catch(err =\u003e console.log('error: ', err));\n}\n\n// add click handler\n\u003cButton onPress={this.addToStorage} title='Add to Storage' /\u003e\n```\n\nThis would create a folder called `textfiles` in our S3 bucket \u0026 store a file called __mytext.txt__ there with the code we specified in the second argument of `Storage.put`.\n\nIf we want to read everything from this folder, we can use `Storage.list`:\n\n```js\nreadFromStorage = () =\u003e {\n  Storage.list('textfiles/')\n    .then(data =\u003e console.log('data from S3: ', data))\n    .catch(err =\u003e console.log('error fetching from S3', err))\n}\n```\n\nIf we only want to read the single file, we can use `Storage.get`:\n\n```js\nreadFromStorage = () =\u003e {\n  Storage.get('textfiles/mytext.txt')\n    .then(data =\u003e {\n      console.log('data from S3: ', data)\n      fetch(data)\n        .then(r =\u003e r.text())\n        .then(text =\u003e {\n          console.log('text: ', text)\n        })\n        .catch(e =\u003e console.log('error fetching text: ', e))\n    })\n    .catch(err =\u003e console.log('error fetching from S3', err))\n}\n```\n\nIf we wanted to pull down everything, we can use `Storage.list`:\n\n```js\nreadFromStorage = () =\u003e {\n  Storage.list('')\n    .then(data =\u003e console.log('data from S3: ', data))\n    .catch(err =\u003e console.log('error fetching from S3', err))\n}\n```\n\n## Multiple Serverless Environments\n\nNow that we have our API up \u0026 running, what if we wanted to update our API but wanted to test it out without it affecting our existing version?\n\nTo do so, we can create a clone of our existing environment, test it out, \u0026 then deploy \u0026 test the new resources.\n\nOnce we are happy with the new feature, we can then merge it back into our main environment. Let's see how to do this!\n\n### Creating a new environment\n\nTo create a new environment, we can run the `env` command:\n\n```sh\n$ amplify env add\n\n\u003e Do you want to use an existing environment? No\n\u003e Enter a name for the environment: apiupdate\n\u003e Do you want to use an AWS profile? Yes\n\u003e Please choose the profile you want to use: appsync-workshop-profile\n```\n\nNow, the new environment has been initialize, \u0026 we can deploy the new environment using the `push` command:\n\n```sh\n$ amplify push\n```\n\nNow that the new environment has been created we can get a list of all available environments using the CLI:\n\n```sh\n$ amplify env list\n```\n\nLet's update the GraphQL schema to add a new field. In __amplify/backend/api/RestaurantAPI/schema.graphql__  update the schema to the following:\n\n```graphql\ntype Restaurant @model {\n  id: ID!\n  clientId: String\n  name: String!\n  type: String\n  description: String!\n  city: String!\n}\n\ntype ModelRestaurantConnection {\n\titems: [Restaurant]\n\tnextToken: String\n}\n\ntype Query {\n  listAllRestaurants(limit: Int, nextToken: String): ModelRestaurantConnection\n}\n```\n\nIn the schema we added a new field to the __Restaurant__ definition to define the type of restaurant:\n\n```graphql\ntype: String\n```\n\nNow, we can run amplify push again to update the API:\n\n```sh\n$ amplify push\n```\n\nTo test this out, we can go into the [AppSync Console](https://console.aws.amazon.com/appsync) \u0026 log into the API.\n\nYou should now see a new API called __RestaurantAPI-apiupdate__. Click on this API to view the API dashboard.\n\nIf you click on __Schema__ you should notice that it has been created with the new __type__ field. Let's try it out.\n\nTo test it out we need to create a new user because we are using a brand new authentication service. To do this, open the app \u0026 sign up.\n\nIn the API dashboard, click on __Queries__.\n\nNext, click on the __Login with User Pools__ link.\n\nCopy the __aws_user_pools_web_client_id__ value from your __aws-exports__ file \u0026 paste it into the __ClientId__ field.\n\nNext, login using your __username__ \u0026 __password__.\n\nNow, create a new mutation \u0026 then query for it:\n\n```graphql\nmutation createRestaurant {\n  createRestaurant(input: {\n    name: \"Nobu\"\n    description: \"Great Sushi\"\n    city: \"New York\"\n    type: \"sushi\"\n  }) {\n    id name description city type\n  }\n}\n\nquery listRestaurants {\n  listAllRestaurants {\n    items {\n      name\n      description\n      city\n      type\n    }\n  }\n}\n```\n\n### Merging the new environment changes into the main environment.\n\nNow that we've created a new environment \u0026 tested it out, let's check out the main environment.\n\n```sh\n$ amplify env checkout local\n```\n\nNext, run the `status` command:\n\n```sh\n$ amplify status\n```\n\nYou should now see an __Update__ operation:\n\n```\nCurrent Environment: local\n\n| Category | Resource name   | Operation | Provider plugin   |\n| -------- | --------------- | --------- | ----------------- |\n| Api      | RestaurantAPI   | Update    | awscloudformation |\n| Auth     | cognito75a8ccb4 | No Change | awscloudformation |\n```\n\nTo deploy the changes, run the push command:\n\n```sh\n$ amplify push\n```\n\nNow, the changes have been deployed \u0026 we can delete the `apiupdate` environment:\n\n```sh\n$ amplify env remove apiupdate\n\nDo you also want to remove all the resources of the environment from the cloud? Y\n```\n\nNow, we should be able to run the `list` command \u0026 see only our main environment:\n\n```sh\n$ amplify env list\n```\n\n## Removing Services\n\nIf at any time, or at the end of this workshop, you would like to delete a service from your project \u0026 your account, you can do this by running the `amplify remove` command:\n\n```sh\n$ amplify remove auth\n\n$ amplify push\n```\n\nIf you are unsure of what services you have enabled at any time, you can run the `amplify status` command:\n\n```sh\n$ amplify status\n```\n\n`amplify status` will give you the list of resources that are currently enabled in your app.\n\n## Deleting the project\n\nTo delete the entire project, run the `delete` command:\n\n```sh\n$ amplify delete\n```\n\n\n\u003c!-- ### GraphQL Subscriptions\n\nNext, let's see how we can create a subscription to subscribe to changes of data in our API.\n\nTo do so, we need to define the subscription, listen for the subscription, \u0026 update the state whenever a new piece of data comes in through the subscription.\n\n```js\n// import the subscription\nimport { onCreateRestaurant } from './src/graphql/subscriptions'\n\n// define the subscription in the class\nsubscription = {}\n\n// subscribe in componentDidMount\ncomponentDidMount() {\n  this.subscription = API.graphql(\n    graphqlOperation(onCreateRestaurant)\n  ).subscribe({\n      next: eventData =\u003e {\n        console.log('eventData', eventData)\n        const restaurant = eventData.value.data.onCreateRestaurant\n        if(CLIENTID === restaurant.clientId) return\n        const restaurants = [...this.state.restaurants, restaurant]\n        this.setState({ restaurants })\n      }\n  });\n}\n\n// remove the subscription in componentWillUnmount\ncomponentWillUnmount() {\n  this.subscription.unsubscribe()\n}\n``` --\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdabit3%2Faws-amplify-workshop-react-native","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdabit3%2Faws-amplify-workshop-react-native","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdabit3%2Faws-amplify-workshop-react-native/lists"}