{"id":16979989,"url":"https://github.com/gsans/components-conf-workshop","last_synced_at":"2026-03-04T03:02:27.718Z","repository":{"id":78168740,"uuid":"206657434","full_name":"gsans/components-conf-workshop","owner":"gsans","description":"Building Full Stack GraphQL Applications with AWS Amplify and React","archived":false,"fork":false,"pushed_at":"2019-09-08T13:47:49.000Z","size":82,"stargazers_count":10,"open_issues_count":0,"forks_count":8,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-08-20T18:52:39.050Z","etag":null,"topics":["awsamplify","awsamplifyclient","awsappsync","react","reactjs"],"latest_commit_sha":null,"homepage":"","language":null,"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/gsans.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2019-09-05T21:06:19.000Z","updated_at":"2023-02-04T23:34:15.000Z","dependencies_parsed_at":"2023-06-19T12:30:42.948Z","dependency_job_id":null,"html_url":"https://github.com/gsans/components-conf-workshop","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/gsans/components-conf-workshop","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gsans%2Fcomponents-conf-workshop","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gsans%2Fcomponents-conf-workshop/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gsans%2Fcomponents-conf-workshop/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gsans%2Fcomponents-conf-workshop/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gsans","download_url":"https://codeload.github.com/gsans/components-conf-workshop/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gsans%2Fcomponents-conf-workshop/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30070479,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-04T01:03:42.280Z","status":"online","status_checked_at":"2026-03-04T02:00:07.464Z","response_time":59,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":["awsamplify","awsamplifyclient","awsappsync","react","reactjs"],"created_at":"2024-10-14T01:48:21.275Z","updated_at":"2026-03-04T03:02:27.712Z","avatar_url":"https://github.com/gsans.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Building Serverless Web Applications with React and AWS Amplify\n\nIn this workshop we'll learn how to build cloud-enabled web applications with GraphQL, React, \u0026 [AWS Amplify](https://aws-amplify.github.io/).\n\n![](./header.jpg)\n\n### Topics we'll be covering:\n\n- [Authentication](#adding-authentication)\n- [GraphQL API with AWS AppSync](#adding-a-graphql-api)\n- [Mocking and Testing](#local-mocking-and-testing)\n- [Adding Authorization to the GraphQL API](#adding-authorization-to-the-graphql-api)\n- [Serverless Functions](#adding-a-serverless-function)\n- [REST API with a Lambda Function](#adding-a-rest-api)\n- [Adding Storage with Amazon S3](#working-with-storage)\n- [Analytics](#adding-analytics)\n- [Multiple Environments](#working-with-multiple-environments)\n- [Deploying via the Amplify Console](#deploying-via-the-amplify-console)\n- [React Native](#react-native)\n- [Removing / Deleting Services](#removing-services)\n- [Appendix](#appendix)\n\n\u003c!-- ## Redeeming our AWS Credit   \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 Application\n\nTo get started, we first need to create a new React project \u0026 change into the new directory using the [Create React App CLI](https://github.com/facebook/create-react-app).\n\nIf you already have this installed, skip to the next step. If not, either install the CLI \u0026 create the app or create a new app using npx:\n\n```bash\nnpm install -g create-react-app\ncreate-react-app my-amplify-app\n```\n\nOr use npx (npm 5.2 \u0026 later) to create a new app:\n\n```bash\nnpx create-react-app my-amplify-app\n```\n\nNow change into the new app directory \u0026 install the AWS Amplify \u0026 AWS Amplify React libraries:\n\n```bash\ncd my-amplify-app\nnpm install --save aws-amplify aws-amplify-react uuid\n# or\nyarn add aws-amplify aws-amplify-react uuid\n```\n\n\u003e If you have issues related to EACCESS try using sudo: `sudo npm \u003ccommand\u003e`.\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\nnpm install -g @aws-amplify/cli\n```\n\u003e If you have issues related to fsevents with npm install. Try: `npm audit fix --force`.\n\nNow we need to configure the CLI with our credentials:\n\n```js\namplify 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: __ap-southeast-2 (Sydney)__\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 Project\n\n```bash\namplify init\n```\n\n- Enter a name for the project: __amplifyreactapp__\n- Enter a name for the environment: __dev__\n- Choose your default editor: __Visual Studio Code (or your default editor)__   \n- Please choose the type of app that you're building __javascript__   \n- What javascript framework are you using __react__   \n- Source Directory Path: __src__   \n- Distribution Directory Path: __build__   \n- Build Command: __npm run-script build__   \n- Start Command: __npm run-script start__   \n- Do you want to use an AWS profile? __Y__\n- Please choose the profile you want to use: __amplify-workshop-user__\n\nNow, the AWS Amplify CLI has iniatilized a new project and you will see a new folder: __amplify__ and a new file called `aws-exports.js` in the __src__ directory. The files in this folder hold your project configuration.\n\n```bash\n\u003camplify-app\u003e\n    |_ amplify\n      |_ .config\n      |_ #current-cloud-backend\n      |_ backend\n      team-provider-info.json\n```\n\n\n## Adding Authentication\n\nTo add authentication, we can use the following command:\n\n```sh\namplify add auth\n```\n\u003e When prompted choose \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__\n- Do you want to configure advanced settings? __Yes, I want to make some additional changes.__\n- What attributes are required for signing up? (Press \u0026lt;space\u0026gt; to select, \u0026lt;a\u0026gt; to \ntoggle all, \u0026lt;i\u0026gt; to invert selection): __Email__\n- Do you want to enable any of the following capabilities? (Press \u0026lt;space\u0026gt; to select, \u0026lt;a\u0026gt; to toggle all, \u0026lt;i\u0026gt; to invert selection): __None__\n\n\u003e To select none just press `Enter` in the last option.\n\nNow, we'll run the push command and the cloud resources will be created in our AWS account.\n\n```bash\namplify push\n```\n\nTo quickly check your newly created __Cognito User Pool__ you can run\n\n```bash\namplify status\n```\n\n\u003e To access the __AWS Cognito Console__ at any time, go to the dashboard at [https://console.aws.amazon.com/cognito/](https://console.aws.amazon.com/cognito/). Also be sure that your region is set correctly.\n\n### Configuring the React application\n\nNow, our resources are created \u0026 we can start using them!\n\nThe first thing we need to do is to configure our React 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 src folder.\n\nTo configure the app, open __src/index.js__ and add the following code below the last import:\n\n```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### Using the withAuthenticator component\n\nTo add authentication, we'll go into __src/App.js__ and first import the `withAuthenticator` HOC (Higher Order Component) from `aws-amplify-react`:\n\n### src/App.js\n\n```js\nimport { withAuthenticator } from 'aws-amplify-react'\n```\n\nNext, we'll wrap our default export (the App component) with the `withAuthenticator` HOC:\n\n```js\nexport default withAuthenticator(App, { includeGreetings: true })\n```\n\n```sh\n# run the app\n\nnpm start\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\n\u003e To view the new user that was created in Cognito, go back to the dashboard at [https://console.aws.amazon.com/cognito/](https://console.aws.amazon.com/cognito/). Also be sure that your region is set correctly.\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### src/App.js\n\n```js\nimport React, { useEffect } from 'react'\nimport { Auth } from 'aws-amplify'\n\nfunction App() {\n  useEffect(() =\u003e {\n    Auth.currentAuthenticatedUser()\n      .then(user =\u003e console.log({ user }))\n      .catch(error =\u003e console.log({ error }))\n  })\n  return (\n    \u003cdiv className=\"App\"\u003e\n      \u003cp\u003e\n        Edit \u003ccode\u003esrc/App.js\u003c/code\u003e and save to reload.\n      \u003c/p\u003e\n    \u003c/div\u003e\n  )\n}\n\nexport default App\n```\n\n### Custom authentication strategies\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 4 user inputs to capture the user's username, email, password, \u0026 phone number.\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\nimport React, { useReducer } from 'react'\n\n// define initial state\nconst initialState = {\n  username: '', password: '', email: ''\n}\n\n// create reducer\nfunction reducer(state, action) {\n  switch(action.type) {\n    case 'SET_INPUT':\n      return { ...state, [action.inputName]: action.inputValue }\n    default:\n      return state\n  }\n}\n\n// useReducer hook creates local state\nconst [state, dispatch] = useReducer(reducer, initialState)\n\n// event handler\nfunction onChange(e) {\n  dispatch({\n    type: 'SET_INPUT',\n    inputName: e.target.name,\n    inputValue: e.target.value\n  })\n}\n\n// example of usage with input\n\u003cinput\n  name='username'\n  placeholder='username'\n  value={state.username}\n  onChange={onChange}\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 this. The Auth class has over 30 methods including things like `signUp`, `signIn`, `confirmSignUp`, `confirmSignIn`, \u0026 `forgotPassword`. These 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\nasync function signUp() {\n  const { username, password, email } = state\n  try {\n    await Auth.signUp({ username, password, attributes: { email }})\n    console.log('user successfully signed up!')\n  } catch (err) {\n    console.log('error signing up user...', err)\n  }\n}\n\n\u003cbutton onClick={signUp}\u003eSign Up\u003c/button\u003e\n```\n\n## Adding a GraphQL API\n\nTo add a GraphQL API, we can use the following command:\n\n```sh\namplify add api\n```\n\nAnswer the following questions\n\n- Please select from one of the above mentioned services __GraphQL__   \n- Provide API name: __CryptoGraphQL__   \n- Choose an authorization type for the API __API key__   \n- Do you have an annotated GraphQL schema? __N__   \n- Do you want a guided schema creation? __Y__   \n- What best describes your project: __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 Coin @model {\n  id: ID!\n  clientId: ID\n  name: String!\n  symbol: String!\n  price: Float!\n}\n```\n\n\u003e Next, let's push the configuration to our account:\n\n```bash\namplify push\n```\n\n- Do you want to generate code for your newly created GraphQL API __Y__\n- Choose the code generation language target: __javascript__\n- Enter the file name pattern of graphql queries, mutations and subscriptions: __(src/graphql/**/*.js)__\n- Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions? __Y__\n- Enter maximum statement depth [increase from default if your schema is deeply nested] __2__\n\nTo view the service you can run the `console` command the feature you'd like to view:\n\n```sh\namplify console api\n```\n\n### Adding mutations from within the AWS AppSync Console\n\nIn the AWS AppSync console, open your API \u0026 then click on Queries.\n\nExecute the following mutation to create a new coin in the API:\n\n```graphql\nmutation createCoin {\n  createCoin(input: {\n    name: \"Bitcoin\"\n    symbol: \"BTC\"\n    price: 9000\n  }) {\n    id name symbol price\n  }\n}\n```\n\nNow, let's query for the coin:\n\n```graphql\nquery listCoins {\n  listCoins {\n    items {\n      id\n      name\n      symbol\n      price\n    }\n  }\n}\n```\n\nWe can even add search / filter capabilities when querying:\n\n```graphql\nquery listCoins {\n  listCoins(filter: {\n    price: {\n      gt: 2000\n    }\n  }) {\n    items {\n      id\n      name\n      symbol\n      price\n    }\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### src/App.js\n\n```js\n// src/App.js\nimport React, { useEffect, useState } from 'react'\n\n// imports from Amplify library\nimport { API, graphqlOperation } from 'aws-amplify'\nimport { withAuthenticator } from 'aws-amplify-react'\n\n// import query\nimport { listCoins } from './graphql/queries'\n\nfunction App() {\n  const [coins, updateCoins] = useState([])\n\n  useEffect(() =\u003e {\n    getData()\n  }, [])\n\n  async function getData() {\n    try {\n      const coinData = await API.graphql(graphqlOperation(listCoins))\n      console.log('data from API: ', coinData)\n      updateCoins(coinData.data.listCoins.items)\n    } catch (err) {\n      console.log('error fetching data..', err)\n    }\n  }\n\n  return (\n    \u003cdiv\u003e\n      {\n        coins.map((c, i) =\u003e (\n          \u003cdiv key={i}\u003e\n            \u003ch2\u003e{c.name}\u003c/h2\u003e\n            \u003ch4\u003e{c.symbol}\u003c/h4\u003e\n            \u003cp\u003e{c.price}\u003c/p\u003e\n          \u003c/div\u003e\n        ))\n      }\n    \u003c/div\u003e\n  )\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. Let's change the component to use a `useReducer` hook.\n\n```js\n// src/App.js\nimport React, { useEffect, useReducer } from 'react'\nimport { API, graphqlOperation } from 'aws-amplify'\nimport { withAuthenticator } from 'aws-amplify-react'\nimport { listCoins } from './graphql/queries'\nimport { createCoin as CreateCoin } from './graphql/mutations'\n\n// import uuid to create a unique client ID\nimport uuid from 'uuid/v4'\n\nconst CLIENT_ID = uuid()\n\n// create initial state\nconst initialState = {\n  name: '', price: '', symbol: '', coins: []\n}\n\n// create reducer to update state\nfunction reducer(state, action) {\n  switch(action.type) {\n    case 'SETCOINS':\n      return { ...state, coins: action.coins }\n    case 'SETINPUT':\n      return { ...state, [action.key]: action.value }\n    default:\n      return state\n  }\n}\n\nfunction App() {\n  const [state, dispatch] = useReducer(reducer, initialState)\n\n  useEffect(() =\u003e {\n    getData()\n  }, [])\n\n  async function getData() {\n    try {\n      const coinData = await API.graphql(graphqlOperation(listCoins))\n      console.log('data from API: ', coinData)\n      dispatch({ type: 'SETCOINS', coins: coinData.data.listCoins.items})\n    } catch (err) {\n      console.log('error fetching data..', err)\n    }\n  }\n\n  async function createCoin() {\n    const { name, price, symbol } = state\n    if (name === '' || price === '' || symbol === '') return\n    const coin = {\n      name, price: parseFloat(price), symbol, clientId: CLIENT_ID\n    }\n    const coins = [...state.coins, coin]\n    dispatch({ type: 'SETCOINS', coins })\n    console.log('coin:', coin)\n    \n    try {\n      await API.graphql(graphqlOperation(CreateCoin, { input: coin }))\n      console.log('item created!')\n    } catch (err) {\n      console.log('error creating coin...', err)\n    }\n  }\n\n  // change state then user types into input\n  function onChange(e) {\n    dispatch({ type: 'SETINPUT', key: e.target.name, value: e.target.value })\n  }\n\n  // add UI with event handlers to manage user input\n  return (\n    \u003cdiv\u003e\n      \u003cinput\n        name='name'\n        placeholder='name'\n        onChange={onChange}\n        value={state.name}\n      /\u003e\n      \u003cinput\n        name='price'\n        placeholder='price'\n        onChange={onChange}\n        value={state.price}\n      /\u003e\n      \u003cinput\n        name='symbol'\n        placeholder='symbol'\n        onChange={onChange}\n        value={state.symbol}\n      /\u003e\n      \u003cbutton onClick={createCoin}\u003eCreate Coin\u003c/button\u003e\n      {\n        state.coins.map((c, i) =\u003e (\n          \u003cdiv key={i}\u003e\n            \u003ch2\u003e{c.name}\u003c/h2\u003e\n            \u003ch4\u003e{c.symbol}\u003c/h4\u003e\n            \u003cp\u003e{c.price}\u003c/p\u003e\n          \u003c/div\u003e\n        ))\n      }\n    \u003c/div\u003e\n  )\n}\n\nexport default withAuthenticator(App, { includeGreetings: true })\n```\n\n### 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 { onCreateCoin } from './graphql/subscriptions'\n\n// update reducer\nfunction reducer(state, action) {\n  switch(action.type) {\n    case 'SETCOINS':\n      return { ...state, coins: action.coins }\n    case 'SETINPUT':\n      return { ...state, [action.key]: action.value }\n    // new �\n    case 'ADDCOIN':\n      return { ...state, coins: [...state.coins, action.coin] }\n    default:\n      return state\n  }\n}\n\n// subscribe in useEffect\nuseEffect(() =\u003e {\n  const subscription = API.graphql(graphqlOperation(onCreateCoin)).subscribe({\n      next: (eventData) =\u003e {\n        const coin = eventData.value.data.onCreateCoin\n        if (coin.clientId === CLIENT_ID) return\n        dispatch({ type: 'ADDCOIN', coin  })\n      }\n  })\n  return () =\u003e subscription.unsubscribe()\n}, [])\n```\n\n## Local mocking and testing\n\nTo mock and test the API locally, you can run the `mock` command:\n\n```sh\namplify mock api\n```\n- Choose the code generation language target: __javascript__\n- Enter the file name pattern of graphql queries, mutations and subscriptions: __src/graphql/**/*.js__\n- Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions: __Y__\n- Enter maximum statement depth [increase from default if your schema is deeply nested]: __2__\n\nThis should open up the local GraphiQL editor.\n\nFrom here, we can now test the API locally.\n\n## Adding Authorization to the GraphQL API\n\nTo add authorization to the API, we can re-configure the API to use our cognito identity pool. To do so, we can run `amplify configure api`:\n\n```sh\namplify configure api\n```\n\n- Please select from one of the below mentioned services: __GraphQL__\n- Choose an authorization type for the API: __Amazon Cognito User Pool__\n\nNext, we'll run `amplify push`:\n\n```sh\namplify push\n```\n\n- Do you want to update code for your updated GraphQL API __N__\n\nNow, we can only access the API with a logged in user.\n\n### Adding fine-grained access controls to the GraphQL API\n\nNext, let's add a field that can only be accessed by the current user.\n\nTo do so, we'll update the schema to add the following new type below the existing Coin type:\n\n```graphql\ntype Note @model @auth(rules: [{allow: owner}]) {\n  id: ID!\n  title: String!\n  description: String\n}\n```\n\nNext, we'll deploy the updates to our API:\n\n```sh\namplify push\n```\n\n- Do you want to update code for your updated GraphQL API: __Y__\n- Do you want to generate GraphQL statements (queries, mutations and subscription) based on your schema types? __Y__\n\nNow, the operations associated with this field will only be accessible by the creator of the item.\n\nTo test it out, try creating a new user \u0026 accessing a note from another user.\n\nTo test the API out in the AWS AppSync console, it will ask for you to __Login with User Pools__. The form will ask you for a __ClientId__. This __ClientId__ is located in __src/aws-exports.js__ in the `aws_user_pools_web_client_id` field.\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\namplify add function\n```\n\n\u003e Answer the following questions\n\n- Provide a friendly name for your resource to be used as a label for this category in the project: __basiclambda__\n- Provide the AWS Lambda function name: __basiclambda__\n- Choose the function template that you want to use: __Hello world function__\n- Do you want to access other resources created in this project from your Lambda function? __No__\n- Do you want to edit the local lambda function now? __Y__\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 = function (event, context) {\n  console.log('event: ', event)\n  const body = {\n    message: \"Hello world!\"\n  }\n  const response = {\n    statusCode: 200,\n    body\n  }\n  context.done(null, response);\n}\n```\n\nNext, we can test this out by running:\n\n```sh\namplify function invoke basiclambda\n```\n\nUsing service: Lambda, provided by: awscloudformation\n- Provide the name of the script file that contains your handler function: __index.js__\n- Provide the name of the handler function to invoke: __handler__\n\nYou'll notice the following output from your terminal:\n\n```sh\nRunning \"lambda_invoke:default\" (lambda_invoke) task\n\nevent:  { key1: 'value1', key2: 'value2', key3: 'value3' }\n\nSuccess!  Message:\n------------------\n{\"statusCode\":200,\"body\":{\"message\":\"Hello world!\"}}\n\nDone.\nDone running invoke function.\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\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\namplify add function\n```\n\n\u003e Answer the following questions\n\n- Provide a friendly name for your resource to be used as a label for this category in the project: __cryptofunction__\n- Provide the AWS Lambda function name: __cryptofunction__\n- Choose the function template that you want to use: __Serverless express function (Integration with Amazon API Gateway)__\n- Do you want to access other resources created in this project from your Lambda function? __No__\n- Do you want to edit the local lambda function now? __Y__\n\n\u003e This should open the function package located at __amplify/backend/function/cryptofunction/src/index.js__.\n\nHere, we'll add the following code \u0026 save the file:\n\n```js\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 last app.use() method, add the following code �\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  console.log(req.query);\n  if (req \u0026\u0026 req.query) {\n    const { start = 0, limit = 10 } = req.query\n    apiUrl = `https://api.coinlore.com/api/tickers/?start=${start}\u0026limit=${limit}`\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\nNext, we'll install axios in the function package:\n\n```sh\ncd amplify/backend/function/cryptofunction/src\n\nnpm install axios\n```\n\nNext, change back into the root directory.\n\nNow we can test this function out:\n\n```sh\namplify function build\namplify function invoke cryptofunction\n```\n\nThis will start up the node server. We can then make `curl` requests agains the endpoint:\n\n```sh\ncurl 'localhost:3000/coins?start=0\u0026limit=1'\n```\n\nIf we'd like to test out the query parameters, we can update the __event.json__ to add the following:\n\n```json\n{\n    \"httpMethod\": \"GET\",\n    \"path\": \"/coins\",\n    \"queryStringParameters\": {\n        \"start\": \"0\",\n        \"limit\": \"1\"\n    }\n}\n```\n\nWhen we invoke the function these query parameters will be passed in \u0026 the http request will be made immediately.\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\namplify add api\n```\n\n\u003e Answer the following questions\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\nNow the resources have been created \u0026 configured \u0026 we can push them to our account: \n\n```bash\namplify push\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// src/App.js\nimport React, { useEffect, useState } from 'react'\nimport { API } from 'aws-amplify'\nimport { withAuthenticator } from 'aws-amplify-react'\n\nfunction App() {\n  const [coins, updateCoins] = useState([])\n\n  async function getData() {\n    try {\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      updateCoins(data.coins)\n    } catch (err) {\n      console.log('error fetching data..', err)\n    }\n  }\n\n  useEffect(() =\u003e {\n    getData()\n  }, [])\n\n  return (\n    \u003cdiv\u003e\n      {\n        coins.map((c, i) =\u003e (\n          \u003cdiv key={i}\u003e\n            \u003ch2\u003e{c.name}\u003c/h2\u003e\n            \u003cp\u003e{c.price_usd}\u003c/p\u003e\n          \u003c/div\u003e\n        ))\n      }\n    \u003c/div\u003e\n  )\n}\n\nexport default withAuthenticator(App, { includeGreetings: true })\n```\n\n#### Challenge\n\nRefactor the above component to use `useReducer` instead of `useState` to add an additional `loading` parameter to the initial state to indicate that the app is fetching and loading when launched.\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: __YOURAPINAME__\n- Please provide bucket name: __YOURUNIQUEBUCKETNAME__\n- Who should have access: __Auth users only__\n- What kind of access do you want for Authenticated users __create/update, read, delete__   \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\nasync function addToStorage() {\n  await Storage.put('javascript/MyReactComponent.js', `\n    import React from 'react'\n    const App = () =\u003e (\n      \u003cp\u003eHello World\u003c/p\u003e\n    )\n    export default App\n  `)\n  console.log('data stored in S3!')\n}\n\n// add click handler\n\u003cbutton onClick={addToStorage}\u003eAdd To Storage\u003c/button\u003e\n```\n\nThis would create a folder called `javascript` in our S3 bucket \u0026 store a file called __MyReactComponent.js__ there with the code we specified in the second argument of `Storage.put`.\n\n\u003e To view the new bucket that was created in S3, go to the dashboard at [https://console.aws.amazon.com/s3](https://console.aws.amazon.com/s3). Also be sure that your region is set correctly.\n\nIf we want to read everything from this folder, we can use `Storage.list`:\n\n```js\nasync function readFolderFromStorage(folder) {\n  const data = await Storage.list(folder) // 'javascript'\n  console.log('Folder: ', data)\n}\n```\n\nIf we only want to read the single file, we can use `Storage.get`:\n\n```js\nasync function readFileFromStorage(file) {\n  const data = await Storage.get(file) // 'javascript/MyReactComponent.js'\n  console.log('File: ', data)\n}\n```\n\nIf we wanted to pull down everything, we can use `Storage.list`:\n\n```js\nasync function readRootFromStorage() {\n  const data = await Storage.list('')\n  console.log('Root: ', data)\n}\n```\n\n### Working with images\n\nHere's how you can store an image:\n\n```js\nfunction App() {\n  async function onChange(e) {\n    const file = e.target.files[0];\n    await Storage.put('example.png', file)\n    console.log('image successfully stored!')\n  }\n\n  return (\n    \u003cinput\n      type=\"file\" accept='image'\n      onChange={(e) =\u003e this.onChange(e)}\n    /\u003e\n  )\n}\n```\n\nHere's how you can read and display an image:\n\n```js\nimport React, { useState } from 'react'\n\nfunction App() {\n  const [imageUrl, updateImage] = useState('')\n\n  async function fetchImage() {\n    const imagePath = await Storage.get('example.png')\n    updateImage(imagePath)\n  }\n\n  return (\n    \u003cdiv\u003e\n      \u003cimg src={imageUrl} /\u003e\n      \u003cbutton onClick={fetchImage}\u003eFetch Image\u003c/button\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\nWe can even use the S3Album component, one of a few components in the AWS Amplify React library to create a pre-configured photo picker:\n\n```js\nimport { S3Album, withAuthenticator } from 'aws-amplify-react'\n\nfunction App() {\n  return (\n    \u003cdiv className=\"App\"\u003e\n      \u003cS3Album path={''} picker /\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n## Adding Analytics\n\nTo add analytics, we can use the following command:\n\n```sh\namplify 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\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 onClick={this.recordEvent}\u003eRecord Event\u003c/button\u003e\n```\n\n## Working with multiple environments\n\nYou can create multiple environments for your application in which to create \u0026 test out new features without affecting the main environment which you are working on.\n\nWhen you create a new environment from an existing environment, you are given a copy of the entire backend application stack from the original project. When you make changes in the new environment, you are then able to test these new changes in the new environment \u0026 merge only the changes that have been made since the new environment was created back into the original environment.\n\nLet's take a look at how to create a new environment. In this new environment, we'll re-configure the GraphQL Schema to have another field for the coin rank.\n\nFirst, we'll initialize a new environment using `amplify env add`:\n\n```sh\namplify 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? Y\n\u003e Please choose the profile you want to use: amplify-workshop-profile\n```\n\nOnce the new environment is initialized, we should be able to see some information about our environment setup by running:\n\n```sh\namplify env list\n\n| Environments |\n| ------------ |\n| dev          |\n| *apiupdate   |\n```\n\nNow we can update the GraphQL Schema in `amplify/backend/api/CryptoGraphQL/schema.graphql` to the following (adding the `rank` field):\n\n```graphql\ntype Coin {\n\tid: ID!\n\tclientId: ID\n\tname: String!\n\tsymbol: String!\n\tprice: Float!\n  rank: Int\n}\n```\n\nNow, we can create this new stack by running `amplify push`:\n\n```sh\namplify push\n```\n\nAfter we test it out, we can now merge it into our original local environment:\n\n```sh\namplify env checkout local\n```\n\nNext, run the `status` command:\n\n```sh\namplify status\n```\n\nYou should now see an __Update__ operation:\n\n```sh\nCurrent Environment: local\n\n| Category | Resource name   | Operation | Provider plugin   |\n| -------- | --------------- | --------- | ----------------- |\n| Api      | CryptoGraphQL   | Update    | awscloudformation |\n| Auth     | cognito75a8ccb4 | No Change | awscloudformation |\n```\n\nTo deploy the changes, run the push command:\n\n```sh\namplify push\n```\n\n- Do you want to update code for your updated GraphQL API? __Y__\n- Do you want to generate GraphQL statements? __Y__\n\nNow, the changes have been deployed \u0026 we can delete the apiupdate environment:\n\n```sh\namplify 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\namplify env list\n```\n\n## Deploying via the Amplify Console\n\nFor hosting, we can use the [Amplify Console](https://aws.amazon.com/amplify/console/) to deploy the application.\n\nThe first thing we need to do is [create a new GitHub repo](https://github.com/new) for this project. Once we've created the repo, we'll copy the URL for the project to the clipboard \u0026 initialize git in our local project:\n\n```sh\ngit init\n\ngit remote add origin git@github.com:username/project-name.git\n\ngit add .\n\ngit commit -m 'initial commit'\n\ngit push origin master\n```\n\nNext we'll visit the Amplify Console in our AWS account at [https://ap-southeast-2.console.aws.amazon.com/amplify/home](https://ap-southeast-2.console.aws.amazon.com/amplify/home).\n\nHere, we'll click __Get Started__ to create a new deployment. Next, authorize Github as the repository service.\n\nNext, we'll choose the new repository \u0026 branch for the project we just created \u0026 click __Next__.\n\nIn the next screen, we'll create a new role \u0026 use this role to allow the Amplify Console to deploy these resources \u0026 click __Next__.\n\nFinally, we can click __Save and Deploy__ to deploy our application!\n\nNow, we can push updates to Master to update our application.\n\n## React Native\n\nAWS Amplify also has framework support for [React Native](https://aws-amplify.github.io/docs/js/start?platform=react-native).\n\nTo get started with using AWS Amplify with React Native, we'll need to install the __AWS Amplify React Native__ package \u0026 then link the dependencies.\n\n```sh\nnpm install aws-amplify-react-native\n\n# If using Expo, you do not need to link these two libraries as they are both part of the Expo SDK.\nreact-native link amazon-cognito-identity-js\nreact-native link react-native-vector-icons\n```\n\nImplementing features with AWS Amplify in React Native is the same as the features implemented in the other steps of this workshop. The only difference is that you will be working with React Native primitives vs HTML elements.\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\namplify remove auth\n\namplify 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\namplify status\n```\n\n`amplify status` will give you the list of resources that are currently enabled in your app.\n\n## Deleting entire project\n\n```sh\namplify delete\n```\n\n## Appendix\n\n### Setup your AWS Account\n\nIn order to follow this workshop you need to create and activate an Amazon Web Services account. \n\nFollow the steps [here](https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account)\n\n### Trobleshooting\n\nMessage: The AWS Access Key Id needs a subscription for the service\n\nSolution: Make sure you are subscribed to the free plan. [Subscribe](https://portal.aws.amazon.com/billing/signup?type=resubscribe#/resubscribed)\n\n\nMessage: TypeError: fsevents is not a constructor\n\nSolution: `npm audit fix --force`","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgsans%2Fcomponents-conf-workshop","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgsans%2Fcomponents-conf-workshop","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgsans%2Fcomponents-conf-workshop/lists"}