{"id":13531571,"url":"https://github.com/dabit3/amplify-photo-sharing-workshop","last_synced_at":"2025-11-17T15:28:47.257Z","repository":{"id":48818495,"uuid":"262454382","full_name":"dabit3/amplify-photo-sharing-workshop","owner":"dabit3","description":"Building full-stack cloud apps with AWS Amplify and React","archived":false,"fork":false,"pushed_at":"2021-07-10T05:07:24.000Z","size":2193,"stargazers_count":208,"open_issues_count":8,"forks_count":60,"subscribers_count":5,"default_branch":"main","last_synced_at":"2025-10-09T09:58:56.865Z","etag":null,"topics":["aws-amplify","dynamodb","graphql","react","serverless"],"latest_commit_sha":null,"homepage":null,"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":"2020-05-09T00:15:05.000Z","updated_at":"2025-03-02T20:12:51.000Z","dependencies_parsed_at":"2022-09-12T03:31:13.370Z","dependency_job_id":null,"html_url":"https://github.com/dabit3/amplify-photo-sharing-workshop","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/dabit3/amplify-photo-sharing-workshop","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabit3%2Famplify-photo-sharing-workshop","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabit3%2Famplify-photo-sharing-workshop/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabit3%2Famplify-photo-sharing-workshop/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabit3%2Famplify-photo-sharing-workshop/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dabit3","download_url":"https://codeload.github.com/dabit3/amplify-photo-sharing-workshop/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dabit3%2Famplify-photo-sharing-workshop/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":284911312,"owners_count":27083421,"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","status":"online","status_checked_at":"2025-11-17T02:00:06.431Z","response_time":55,"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":["aws-amplify","dynamodb","graphql","react","serverless"],"created_at":"2024-08-01T07:01:04.055Z","updated_at":"2025-11-17T15:28:47.226Z","avatar_url":"https://github.com/dabit3.png","language":"JavaScript","funding_links":[],"categories":["Workshops"],"sub_categories":[],"readme":"# Build a Photo Sharing App with React and AWS Amplify\n\nIn this workshop we'll learn how to build a full stack cloud application with React, GraphQL, \u0026 [Amplify](https://docs.amplify.aws/).\n\n![Build a Photo Sharing App with React and AWS Amplify](banner.jpg)\n\n### Overview\n\nWe'll start from scratch, using the [Create React App CLI](https://reactjs.org/docs/create-a-new-react-app.html#create-react-app) to create a new React web project. We'll then, step by step, use the [Amplify CLI](https://github.com/aws-amplify/amplify-cli) to build out and configure our cloud infrastructure and then use the [Amplify JS Libraries](https://github.com/aws-amplify/amplify-js) to connect the React client application to the APIs we create using the CLI.\n\nThe app will be a basic CRUD + List app with real-time updates. When you think of many types of applications like Instagram, Twitter, or Facebook, they consist of a list of items and often the ability to drill down into a single item view. The app we will be building will be very similar to this, displaying a list of posts with images and data like the name, location, and description of the post. You will also be able to see only a view containing only a list of your own posts.\n\nThis workshop should take you anywhere between 2 to 5 hours to complete.\n\n### Environment\n\nBefore we begin, make sure you have the following installed:\n\n- Node.js v10.x or later\n- npm v5.x or later\n- git v2.14.1 or later\n\nWe will be working from a terminal using a [Bash shell](https://en.wikipedia.org/wiki/Bash_(Unix_shell)) to run Amplify CLI commands to provision infrastructure and also to run a local version of the React web app and test it in a web browser.\n\n### Background needed / level\n\nThis workshop is intended for intermediate to advanced front end \u0026 back end developers wanting to learn more about full stack serverless development.\n\nWhile some level of React and GraphQL is helpful, this workshop requires zero previous knowledge about React or GraphQL.\n\n### Topics we'll be covering:\n\n- GraphQL API with AWS AppSync\n- Authentication\n- Object (image) storage\n- Authorization\n- Hosting\n- Deleting the resources\n\n## Getting Started - Creating the React Application\n\nTo get started, we first need to create a new React project using the [Create React App CLI](https://github.com/facebook/create-react-app).\n\n```bash\n$ npx create-react-app postagram\n```\n\nNow change into the new app directory \u0026 install AWS Amplify, AWS Amplify UI React, react-router-dom, emotion, \u0026 uuid:\n\n```bash\n$ cd postagram\n$ npm install aws-amplify emotion uuid react-router-dom @aws-amplify/ui-react\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\u003e If you'd like to see a video walkthrough of this configuration process, click [here](https://www.youtube.com/watch?v=fWbM5DLh25U).\n\n```sh\n$ amplify configure\n\n- Specify the AWS Region: us-east-1 || us-west-2 || eu-central-1\n- Specify the username of the new IAM user: amplify-cli-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-cli-user\n```\n\n### Initializing A New Project\n\n```bash\n$ amplify init\n\n- Enter a name for the project: postagram\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 youre 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-cli-user\n```\n\nThe Amplify CLI has initialized a new project \u0026 you will see a new folder: __amplify__ \u0026 a new file called `aws-exports.js` in the __src__ directory. These files hold your project configuration.\n\nTo view the status of the amplify project at any time, you can run the Amplify `status` command:\n\n```sh\n$ amplify status\n```\n\nTo view the amplify project in the Amplify console at any time, run the `console` command:\n\n```sh\n$ amplify console\n```\n\n## Adding an AWS AppSync GraphQL API\n\nTo add a GraphQL 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: GraphQL\n? Provide API name: Postagram\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 (1-365): 365 (or your preferred expiration)\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\n? Do you want to edit the schema now? (Y/n) Y\n```\n\nThe CLI should open this GraphQL schema in your text editor.\n\n__amplify/backend/api/Postagram/schema.graphql__\n\nUpdate the schema to the following:   \n\n```graphql\ntype Post @model {\n  id: ID!\n  name: String!\n  location: String!\n  description: String!\n  image: String\n}\n```\n\nAfter saving the schema, go back to the CLI and press enter.\n\n### Deploying the API\n\nTo deploy the API, run the push command:\n\n```\n$ amplify push\n\n? Are you sure you want to continue? Y\n\n# You will be walked through the following questions for GraphQL code generation\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? Yes\n? Enter maximum statement depth [increase from default if your schema is deeply nested]: 2\n```\n\n\u003e Alternately, you can run `amplify push -y` to answer __Yes__ to all questions.\n\nNow the API is live and you can start interacting with it!\n\n\n### Testing the API\n\nTo test it out we can use the GraphiQL editor in the AppSync dashboard. To open the AppSync dashboard, run the following command:\n\n```sh\n$ amplify console api\n\n\u003e Choose GraphQL\n```\n\nIn the AppSync dashboard, click on __Queries__ to open the GraphiQL editor. In the editor, create a new post with the following mutation:\n\n```graphql\nmutation createPost {\n  createPost(input: {\n    name: \"My first post\"\n    location: \"New York\"\n    description: \"Best burgers in NYC - Jackson Hole\"\n  }) {\n    id\n    name\n    location\n    description\n  }\n}\n```\n\nThen, query for the posts:\n\n```graphql\nquery listPosts {\n  listPosts {\n    items {\n      id\n      name\n      location\n      description\n    }\n  }\n}\n```\n\n### Configuring the React applicaion\n\nNow, our API is created \u0026 we can test it out in our app!\n\nThe first thing we need to do is to configure our React application to be aware of our 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### Interacting with the GraphQL API from our client application - Querying for data\n\nNow that the GraphQL API is running we can begin interacting with it. The 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\nThe main thing to notice in this component is the API call. Take a look at this piece of code:\n\n```js\n/* Call API.graphql, passing in the query that we'd like to execute. */\nconst postData = await API.graphql({ query: listPosts });\n```\n\n#### src/App.js\n\n```js\n// src/App.js\nimport React, { useState, useEffect } from 'react';\n\n// import API from Amplify library\nimport { API } from 'aws-amplify'\n\n// import query definition\nimport { listPosts } from './graphql/queries'\n\nexport default function App() {\n  const [posts, setPosts] = useState([])\n  useEffect(() =\u003e {\n    fetchPosts();\n  }, []);\n  async function fetchPosts() {\n    try {\n      const postData = await API.graphql({ query: listPosts });\n      setPosts(postData.data.listPosts.items)\n    } catch (err) {\n      console.log({ err })\n    }\n  }\n  return (\n    \u003cdiv\u003e\n      \u003ch1\u003eHello World\u003c/h1\u003e\n      {\n        posts.map(post =\u003e (\n          \u003cdiv key={post.id}\u003e\n            \u003ch3\u003e{post.name}\u003c/h3\u003e\n            \u003cp\u003e{post.location}\u003c/p\u003e\n          \u003c/div\u003e\n        ))\n      }\n    \u003c/div\u003e\n  )\n}\n```\n\nIn the above code we are using `API.graphql` to call the GraphQL API, and then taking the result from that API call and storing the data in our state. This should be the list of posts you created via the GraphiQL editor.\n\nNext, test the app:\n\n```sh\n$ npm start\n```\n\n## Adding Authentication\n\nNext, let's update the app to add authentication.\n\nTo add the authentication service, we can use the following command:\n\n```sh\n$ amplify add auth\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\n? Do you want to configure advanced settings? No, I am done.   \n```\n\nTo deploy the authentication service, you can run the `push` command:\n\n```sh\n$ amplify push\n\n? Are you sure you want to continue? Yes\n```\n\n### Using the withAuthenticator component\n\nTo add authentication in the React app, we'll go into __src/App.js__ and first import the `withAuthenticator` HOC (Higher Order Component) from `@aws-amplify/ui-react`:\n\n```js\n// src/App.js, import the withAuthenticator component\nimport { withAuthenticator } from '@aws-amplify/ui-react'\n```\n\nNext, we'll wrap our default export (the App component) with the `withAuthenticator` HOC:\n\n```js\nfunction App() {/* existing code here, no changes */}\n\n/* src/App.js, change the default export to this: */\nexport default withAuthenticator(App)\n```\n\nNext test it out in the browser:\n\n```sh\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\nOnce you sign up, check your email to confirm the sign up.\n\nNow that you have the authentication service created, you can view it any time in the console by running the following command:\n\n```sh\n$ amplify console auth\n\n\u003e Choose User Pool\n```\n\n### Adding a sign out button\n\nYou can also easily add a preconfigured UI component for signing out.\n\n```js\nimport { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react';\n\n/* Somewhere in the UI */\n\u003cAmplifySignOut /\u003e\n```\n\n### Styling the UI components\n\nNext, let's update the UI component styling by setting styles for the `:root` pseudoclass.\n\nTo do so, open __src/index.css__ and add the following styling:\n\n```css\n:root {\n  --amplify-primary-color: #006eff;\n  --amplify-primary-tint: #005ed9;\n  --amplify-primary-shade: #005ed9;\n}\n```\n\n\u003e To learn more about theming the Amplify React UI components, check out the documentation [here](https://docs.amplify.aws/ui/customization/theming/q/framework/react)\n\n### Accessing User Data\n\nWe can access the user's info now that they are signed in by calling `Auth.currentAuthenticatedUser()` in `useEffect`.\n\n```js\nimport { API, Auth } from 'aws-amplify'\n\nuseEffect(() =\u003e {\n  fetchPosts();\n  checkUser(); // new function call\n});\n\nasync function checkUser() {\n  const user = await Auth.currentAuthenticatedUser();\n  console.log('user: ', user);\n  console.log('user attributes: ', user.attributes);\n}\n```\n\n## Image Storage with Amazon S3\n\nThe last feature we need to have is image storage. To add image storage, we'll use Amazon S3. Amazon S3 can be configured and created via the Amplify CLI:\n\n```sh\n$ amplify add storage\n\n? Please select from one of the below mentioned services: Content\n? Please provide a friendly name for your resource that will be used to label this category in the project: images\n? Please provide bucket name: postagram14148f2f4aeb4f259c847e1e27145a2 \u003cuse_default\u003e\n? Who should have access: Auth and guest users\n? What kind of access do you want for Authenticated users? create, update, read, delete\n? What kind of access do you want for Guest users? read\n? Do you want to add a Lambda Trigger for your S3 Bucket? N\n```\n\nTo deploy the service, run the following command:\n\n```sh\n$ amplify push\n```\n\nTo save items to S3, we use the `Storage` API. The `Storage` API works like this.\n\n1. Saving an item:\n\n```js\nconst file = e.target.files[0];\nawait Storage.put(file.name, file);\n```\n\n2. Getting an item:\n\n```js\nconst image = await Storage.get('my-image-key.jpg')\n```\n\nWhen fetching an item using the Storage category, Amplify will automatically retrieve the item with a [pre-signed url](https://docs.aws.amazon.com/AmazonS3/latest/dev/ShareObjectPreSignedURL.html) allowing the user to view the item.\n\n### Creating a basic photo album\n\nLet's update our code to implement a photo picker and photo album.\n\nWhen the app loads, we will make an API call to S3 to list the images in the bucket and render them to the screen.\n\nWhen a user uploads a new image, we'll also refresh the list of images along with the new image.\n\n```js\n// src/App.js\nimport React, { useState, useEffect } from 'react';\nimport { Storage } from 'aws-amplify'\nimport { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react'\nimport { v4 as uuid } from 'uuid'\n\nfunction App() {\n  const [images, setImages] = useState([])\n  useEffect(() =\u003e {\n    fetchImages()\n  }, [])\n  async function fetchImages() {\n    // Fetch list of images from S3\n    let s3images = await Storage.list('')\n    // Get presigned URL for S3 images to display images in app\n    s3images = await Promise.all(s3images.map(async image =\u003e {\n      const signedImage = await Storage.get(image.key)\n      return signedImage\n    }))\n    setImages(s3images)\n  }\n  function onChange(e) {\n    if (!e.target.files[0]) return\n    const file = e.target.files[0];\n    // upload the image then fetch and rerender images\n    Storage.put(uuid(), file).then (() =\u003e fetchImages())\n  }\n\n  return (\n    \u003cdiv\u003e\n      \u003ch1\u003ePhoto Album\u003c/h1\u003e\n      \u003cspan\u003eAdd new image\u003c/span\u003e\n      \u003cinput\n        type=\"file\"\n        accept='image/png'\n        onChange={onChange}\n      /\u003e\n      \u003cdiv style={{display: 'flex', flexDirection: 'column'}}\u003e\n      { images.map(image =\u003e \u003cimg src={image} style={{width: 400, marginBottom: 10}} /\u003e) }\n      \u003c/div\u003e\n      \u003cAmplifySignOut /\u003e\n    \u003c/div\u003e\n  );\n}\n\nexport default withAuthenticator(App);\n```\n\nNow we can start saving images to S3 and we can also download and view them using the Storage category from AWS Amplify.\n\nTo view the images as well as your S3 bucket at any time, do the following:\n\n1. Run `amplify console` from your terminal\n2. Click on the __File Storage__ tab\n3. Click on __View in S3__ in the top right corner\n4. Click on the __public__ bucket\n\nNext, we'll continue by building the Photo Sharing App Travel app.\n\n# Photo Sharing App Travel App\n\nNow that we have the services we need, let's continue by building out the front end of the app.\n\n### Creating the folder structure for our app\n\nNext, create the following files in the __src__ directory:\n\n```sh\nButton.js\nCreatePost.js\nHeader.js\nPost.js\nPosts.js\n```\n\nNext, we'll go one by one and update these files with our new code.\n\n### Button.js\n\nHere, we will create a button that we'll be reusing across the app:\n\n```js\nimport React from 'react';\nimport { css } from 'emotion';\n\nexport default function Button({\n  title, onClick, type = \"action\"\n}) {\n  return (\n    \u003cbutton className={buttonStyle(type)} onClick={onClick}\u003e\n      { title }\n    \u003c/button\u003e\n  )\n}\n\nconst buttonStyle = type =\u003e css`\n  background-color: ${type === \"action\" ? \"black\" : \"red\"};\n  height: 40px;\n  width: 160px;\n  font-weight: 600;\n  font-size: 16px;\n  color: white;\n  outline: none;\n  border: none;\n  margin-top: 5px;\n  cursor: pointer;\n  :hover {\n    background-color: #363636;\n  }\n`\n```\n\n### Header.js\n\nAdd the following code in __Header.js__\n\n```js\nimport React from 'react';\nimport { css } from 'emotion';\nimport { Link } from 'react-router-dom';\n\nexport default function Header() {\n  return (\n    \u003cdiv className={headerContainer}\u003e\n      \u003ch1 className={headerStyle}\u003ePostagram\u003c/h1\u003e\n      \u003cLink to=\"/\" className={linkStyle}\u003eAll Posts\u003c/Link\u003e\n    \u003c/div\u003e\n  )\n}\n\nconst headerContainer = css`\n  padding-top: 20px;\n`\n\nconst headerStyle = css`\n  font-size: 40px;\n  margin-top: 0px;\n`\n\nconst linkStyle = css`\n  color: black;\n  font-weight: bold;\n  text-decoration: none;\n  margin-right: 10px;\n  :hover {\n    color: #058aff;\n  }\n`\n```\n\n## Posts.js\n\nThe next thing we'll do is create the __Posts__ component to render a list of posts.\n\nThis will go in the main view of the app. The only data from the post that will be rendered in this view is the post name and post image.\n\nThe `posts` array will be passed in as a prop to the __Posts__ component.\n\n```js\nimport React from 'react'\nimport { css } from 'emotion';\nimport { Link } from 'react-router-dom';\n\nexport default function Posts({\n  posts = []\n}) {\n  return (\n    \u003c\u003e\n      \u003ch1\u003ePosts\u003c/h1\u003e\n      {\n        posts.map(post =\u003e (\n          \u003cLink to={`/post/${post.id}`} className={linkStyle} key={post.id}\u003e\n            \u003cdiv key={post.id} className={postContainer}\u003e\n              \u003ch1 className={postTitleStyle}\u003e{post.name}\u003c/h1\u003e\n              \u003cimg alt=\"post\" className={imageStyle} src={post.image} /\u003e\n            \u003c/div\u003e\n          \u003c/Link\u003e\n        ))\n      }\n    \u003c/\u003e\n  )\n}\n\nconst postTitleStyle = css`\n  margin: 15px 0px;\n  color: #0070f3;\n`\n\nconst linkStyle = css`\n  text-decoration: none;\n`\n\nconst postContainer = css`\n  border-radius: 10px;\n  padding: 1px 20px;\n  border: 1px solid #ddd;\n  margin-bottom: 20px;\n  :hover {\n    border-color: #0070f3;\n  }\n`\n\nconst imageStyle = css`\n  width: 100%;\n  max-width: 400px;\n`\n```\n\n## CreatePost.js\n\nThe next component we'll create is `CreatePost`. This component is a form that will be displayed to the user as an `overlay` or a `modal`. In it, the user will be able to toggle the overlay to show and hide it, and also be able to create a new post.\n\nThe props this component will receive are the following:\n\n1. `updateOverlayVisibility` - This function will toggle the overlay to show / hide it\n2. `updatePosts` - This function will allow us to update the main posts array\n3. `posts` - The posts coming back from our API\n\nThis component has a lot going on, so before we dive into the code let's walk through what is happening:\n\n1. We create some initial state using the `useState` hook. This state is created using the `initialState` object.\n2. The `onChangeText` handler sets the name, description, and location fields of the post\n3. The `onChangeImage` handler allows the user to upload an image and saves it to state. It also creates a unique image name.\n4. The `save` function does the following:\n- First checks to make sure that all of the form fields are populated\n- Next it updates the `saving` state to true to show a saving indicator \n- We then create a unique ID for the post using the `uuid` library\n- Using the form state and the `uuid`, we create a post object that will be sent to the API.\n- Next, we upload the image to S3 using `Storage.put`, passing in the image name and the file\n- Once the image upload is successful, we create the `post` in our GraphQL API\n- Finally, we update the local state, close the popup, and update the local `posts` array with the new post\n\n```js\nimport React, { useState } from 'react';\nimport { css } from 'emotion';\nimport Button from './Button';\nimport { v4 as uuid } from 'uuid';\nimport { Storage, API, Auth } from 'aws-amplify';\nimport { createPost } from './graphql/mutations';\n\n/* Initial state to hold form input, saving state */\nconst initialState = {\n  name: '',\n  description: '',\n  image: {},\n  file: '',\n  location: '',\n  saving: false\n};\n\nexport default function CreatePost({\n  updateOverlayVisibility, updatePosts, posts\n}) {\n  /* 1. Create local state with useState hook */\n  const [formState, updateFormState] = useState(initialState)\n\n  /* 2. onChangeText handler updates the form state when a user types into a form field */\n  function onChangeText(e) {\n    e.persist();\n    updateFormState(currentState =\u003e ({ ...currentState, [e.target.name]: e.target.value }));\n  }\n\n  /* 3. onChangeFile handler will be fired when a user uploads a file  */\n  function onChangeFile(e) {\n    e.persist();\n    if (! e.target.files[0]) return;\n    const image = { fileInfo: e.target.files[0], name: `${e.target.files[0].name}_${uuid()}`}\n    updateFormState(currentState =\u003e ({ ...currentState, file: URL.createObjectURL(e.target.files[0]), image }))\n  }\n\n  /* 4. Save the post  */\n  async function save() {\n    try {\n      const { name, description, location, image } = formState;\n      if (!name || !description || !location || !image.name) return;\n      updateFormState(currentState =\u003e ({ ...currentState, saving: true }));\n      const postId = uuid();\n      const postInfo = { name, description, location, image: formState.image.name, id: postId };\n\n      await Storage.put(formState.image.name, formState.image.fileInfo);\n      await API.graphql({\n        query: createPost, variables: { input: postInfo }\n      });\n      updatePosts([...posts, { ...postInfo, image: formState.file }]);\n      updateFormState(currentState =\u003e ({ ...currentState, saving: false }));\n      updateOverlayVisibility(false);\n    } catch (err) {\n      console.log('error: ', err);\n    }\n  }\n\n  return (\n    \u003cdiv className={containerStyle}\u003e\n      \u003cinput\n        placeholder=\"Post name\"\n        name=\"name\"\n        className={inputStyle}\n        onChange={onChangeText}\n      /\u003e\n      \u003cinput\n        placeholder=\"Location\"\n        name=\"location\"\n        className={inputStyle}\n        onChange={onChangeText}\n      /\u003e\n      \u003cinput\n        placeholder=\"Description\"\n        name=\"description\"\n        className={inputStyle}\n        onChange={onChangeText}\n      /\u003e\n      \u003cinput \n        type=\"file\"\n        onChange={onChangeFile}\n      /\u003e\n      { formState.file \u0026\u0026 \u003cimg className={imageStyle} alt=\"preview\" src={formState.file} /\u003e }\n      \u003cButton title=\"Create New Post\" onClick={save} /\u003e\n      \u003cButton type=\"cancel\" title=\"Cancel\" onClick={() =\u003e updateOverlayVisibility(false)} /\u003e\n      { formState.saving \u0026\u0026 \u003cp className={savingMessageStyle}\u003eSaving post...\u003c/p\u003e }\n    \u003c/div\u003e\n  )\n}\n\nconst inputStyle = css`\n  margin-bottom: 10px;\n  outline: none;\n  padding: 7px;\n  border: 1px solid #ddd;\n  font-size: 16px;\n  border-radius: 4px;\n`\n\nconst imageStyle = css`\n  height: 120px;\n  margin: 10px 0px;\n  object-fit: contain;\n`\n\nconst containerStyle = css`\n  display: flex;\n  flex-direction: column;\n  width: 400px;\n  height: 420px;\n  position: fixed;\n  left: 0;\n  border-radius: 4px;\n  top: 0;\n  margin-left: calc(50vw - 220px);\n  margin-top: calc(50vh - 230px);\n  background-color: white;\n  border: 1px solid #ddd;\n  box-shadow: rgba(0, 0, 0, 0.25) 0px 0.125rem 0.25rem;\n  padding: 20px;\n`\n\nconst savingMessageStyle = css`\n  margin-bottom: 0px;\n`\n```\n\n## Post.js\n\nThe next component that we'll build is the Post component.\n\nIn this component, we will be reading the post `id` from the router parameters. We'll then use this post `id` to make an API call to the GraphQL API to fetch the post details.\n\nAnother thing to look at is how we deal with images.\n\nWhen storing an image in S3, we\n\n```js\nimport React, { useState, useEffect } from 'react'\nimport { css } from 'emotion';\nimport { useParams } from 'react-router-dom';\nimport { API, Storage } from 'aws-amplify';\nimport { getPost } from './graphql/queries';\n\nexport default function Post() {\n  const [loading, updateLoading] = useState(true);\n  const [post, updatePost] = useState(null);\n  const { id } = useParams()\n  useEffect(() =\u003e {\n    fetchPost()\n  }, [])\n  async function fetchPost() {\n    try {\n      const postData = await API.graphql({\n        query: getPost, variables: { id }\n      });\n      const currentPost = postData.data.getPost\n      const image = await Storage.get(currentPost.image);\n\n      currentPost.image = image;\n      updatePost(currentPost);\n      updateLoading(false);\n    } catch (err) {\n      console.log('error: ', err)\n    }\n  }\n  if (loading) return \u003ch3\u003eLoading...\u003c/h3\u003e\n  console.log('post: ', post)\n  return (\n    \u003c\u003e\n      \u003ch1 className={titleStyle}\u003e{post.name}\u003c/h1\u003e\n      \u003ch3 className={locationStyle}\u003e{post.location}\u003c/h3\u003e\n      \u003cp\u003e{post.description}\u003c/p\u003e\n      \u003cimg alt=\"post\" src={post.image} className={imageStyle} /\u003e\n    \u003c/\u003e\n  )\n}\n\nconst titleStyle = css`\n  margin-bottom: 7px;\n`\n\nconst locationStyle = css`\n  color: #0070f3;\n  margin: 0;\n`\n\nconst imageStyle = css`\n  max-width: 500px;\n  @media (max-width: 500px) {\n    width: 100%;\n  }\n`\n```\n\n## Router - App.js\n\nNext, create the router in App.js. Our app will have two main routes:\n\n1. A home route - `/`. This route will render a list of posts from our API\n2. A post details route - `/post/:id`. This route will render a single post and details about that post.\n\nUsing React Router, we can read the Post ID from the route and fetch the post associated with it. This is a common pattern in many apps as it makes the link shareable.\n\nAnother way to do this would be to have some global state management set up and setting the post ID in the global state. The main drawback of this approach is that the URL cannot be shared.\n\nOther than routing, the main functionality happening in this component is an `API` call to fetch posts from our API.\n\n```js\nimport React, { useState, useEffect } from \"react\";\nimport {\n  HashRouter,\n  Switch,\n  Route\n} from \"react-router-dom\";\nimport { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react';\nimport { css } from 'emotion';\nimport { API, Storage, Auth } from 'aws-amplify';\nimport { listPosts } from './graphql/queries';\n\nimport Posts from './Posts';\nimport Post from './Post';\nimport Header from './Header';\nimport CreatePost from './CreatePost';\nimport Button from './Button';\n\nfunction Router() {\n  /* create a couple of pieces of initial state */\n  const [showOverlay, updateOverlayVisibility] = useState(false);\n  const [posts, updatePosts] = useState([]);\n\n  /* fetch posts when component loads */\n  useEffect(() =\u003e {\n      fetchPosts();\n  }, []);\n  async function fetchPosts() {\n    /* query the API, ask for 100 items */\n    let postData = await API.graphql({ query: listPosts, variables: { limit: 100 }});\n    let postsArray = postData.data.listPosts.items;\n    /* map over the image keys in the posts array, get signed image URLs for each image */\n    postsArray = await Promise.all(postsArray.map(async post =\u003e {\n      const imageKey = await Storage.get(post.image);\n      post.image = imageKey;\n      return post;\n    }));\n    /* update the posts array in the local state */\n    setPostState(postsArray);\n  }\n  async function setPostState(postsArray) {\n    updatePosts(postsArray);\n  }\n  return (\n    \u003c\u003e\n      \u003cHashRouter\u003e\n          \u003cdiv className={contentStyle}\u003e\n            \u003cHeader /\u003e\n            \u003chr className={dividerStyle} /\u003e\n            \u003cButton title=\"New Post\" onClick={() =\u003e updateOverlayVisibility(true)} /\u003e\n            \u003cSwitch\u003e\n              \u003cRoute exact path=\"/\" \u003e\n                \u003cPosts posts={posts} /\u003e\n              \u003c/Route\u003e\n              \u003cRoute path=\"/post/:id\" \u003e\n                \u003cPost /\u003e\n              \u003c/Route\u003e\n            \u003c/Switch\u003e\n          \u003c/div\u003e\n          \u003cAmplifySignOut /\u003e\n        \u003c/HashRouter\u003e\n        { showOverlay \u0026\u0026 (\n          \u003cCreatePost\n            updateOverlayVisibility={updateOverlayVisibility}\n            updatePosts={setPostState}\n            posts={posts}\n          /\u003e\n        )}\n    \u003c/\u003e\n  );\n}\n\nconst dividerStyle = css`\n  margin-top: 15px;\n`\n\nconst contentStyle = css`\n  min-height: calc(100vh - 45px);\n  padding: 0px 40px;\n`\n\nexport default withAuthenticator(Router);\n```\n\n### Deleting the existing data\n\nNow the app is ready to test out, but before we do let's delete the existing data in the database. To do so, follow these steps:\n\n1. Open the Amplify Console\n\n```sh\n$ amplify console\n```\n\n2. Click on __API__, then click on __PostTable__ under the __Data sources__ tab.\n\n3. Click on the __Items__ tab.\n\n4. Select the items in the database and delete them by choosing __Delete__ from the __Actions__ button.\n\n### Testing the app\n\nNow we can try everything out. To start the app, run the `start` command:\n\n```sh\n$ npm start\n```\n\n## Hosting\n\nThe Amplify Console is a hosting service with continuous integration and deployment.\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\n$ git init\n\n$ git remote add origin git@github.com:username/project-name.git\n\n$ git add .\n\n$ git commit -m 'initial commit'\n\n$ git push origin master\n```\n\nNext we'll visit the Amplify Console for the app we've already deployed:\n\n```sh\n$ amplify console\n```\n\nIn the __Frontend Environments__ section, under __Connect a frontend web app__ choose __GitHub__ then then click on __Connect branch__.\n\nNext, under \"Frontend environments\", 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## Adding Authorization to the GraphQL API\n\nYou can update the AppSync API to enable multiple authorization modes.\n\nIn this example, we will update the API to use the both Cognito and API Key to enable a combination of public and private access. This will also enable us to implement authorization for the API.\n\nTo enable multiple authorization modes, reconfigure the API:\n\n```sh\n$ amplify update api\n\n? Please select from one of the below mentioned services: GraphQL   \n? Select from the options below: Update auth settings\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 (1-365): 365 \u003cor your preferred expiration\u003e\n? Configure additional auth types? Y\n? Choose the additional authorization types you want to configure for the API: Amazon Cognito User Pool\n```\n\nNow, update the GraphQL schema to the following:\n\n__amplify/backend/api/Postagram/schema.graphql__\n\n```graphql\ntype Post @model\n  @auth(rules: [\n    { allow: owner },\n    { allow: public, operations: [read] },\n    { allow: private, operations: [read] }\n  ]) {\n  id: ID!\n  name: String!\n  location: String!\n  description: String!\n  image: String\n  owner: String\n}\n```\n\nDeploy the changes:\n\n```sh\n$ amplify push -y\n```\n\nNow, you will have two types of API access:\n\n1. Private (Cognito) - to create a post, a user must be signed in. Once they have created a post, they can update and delete their own post. They can also read all posts.\n2. Public (API key) - Any user, regardless if they are signed in, can query for posts or a single post.\n\nUsing this combination, you can easily query for just a single user's posts or for all posts.\n\nTo make this secondary private API call from the client, the authorization type needs to be specified in the query or mutation:\n\n```js\nconst postData = await API.graphql({\n  mutation: createPost,\n  authMode: 'AMAZON_COGNITO_USER_POOLS',\n  variables: {\n    input: postInfo\n  }\n});\n```\n\n### Adding a new route to view only your own posts\n\nNext we will update the app to create a new route for viewing only the posts that we've created.\n\nTo do so, first open __CreatePost.js__ and update the `save` mutation with the following to specify the `authmode` and set the owner of the post in the local state:\n\n```js\nasync function save() {\n  try {\n    const { name, description, location, image } = formState;\n    if (!name || !description || !location || !image.name) return;\n    updateFormState(currentState =\u003e ({ ...currentState, saving: true }));\n    const postId = uuid();\n    const postInfo = { name, description, location, image: formState.image.name, id: postId };\n\n    await Storage.put(formState.image.name, formState.image.fileInfo);\n    await API.graphql({\n      query: createPost,\n      variables: { input: postInfo },\n      authMode: 'AMAZON_COGNITO_USER_POOLS'\n    }); // updated\n    const { username } = await Auth.currentAuthenticatedUser(); // new\n    updatePosts([...posts, { ...postInfo, image: formState.file, owner: username }]); // updated\n    updateFormState(currentState =\u003e ({ ...currentState, saving: false }));\n    updateOverlayVisibility(false);\n  } catch (err) {\n    console.log('error: ', err);\n  }\n}\n```\n\nNext, open __App.js__.\n\nCreate a new piece of state to hold your own posts named `myPosts`:\n\n```js\nconst [myPosts, updateMyPosts] = useState([]);\n```\n\nNext, in the `setPostState` method, update `myPosts` with posts from the signed in user:\n\n```js\nasync function setPostState(postsArray) {\n  const user = await Auth.currentAuthenticatedUser();\n  const myPostData = postsArray.filter(p =\u003e p.owner === user.username);\n  updateMyPosts(myPostData);\n  updatePosts(postsArray);\n}\n```\n\nNow, add a new route to show your posts:\n\n```js\n\u003cRoute exact path=\"/myposts\" \u003e\n  \u003cPosts posts={myPosts} /\u003e\n\u003c/Route\u003e\n```\n\nFinally, open __Header.js__ and add a link to the new route:\n\n```js\n\u003cLink to=\"/myposts\" className={linkStyle}\u003eMy Posts\u003c/Link\u003e\n```\n\nNext, test it out:\n\n```sh\n$ npm start\n```\n\n## Additional learning \u0026 use cases\n\n### Relationships\n\nWhat if we wanted to create a relationship between the Post and another type.\n\nIn this example, we add a new `Comment` type and create a relationship using the `@connection` directive. Doing this will enable a one to many relationship between `Post` and `Comment` types.\n\n```graphql\n# amplify/backend/api/Postagram/schema.graphql\n\ntype Post @model\n  @auth(rules: [\n    { allow: owner },\n    { allow: public, operations: [read] },\n    { allow: private, operations: [read] }\n  ]) {\n  id: ID!\n  name: String!\n  location: String!\n  description: String!\n  image: String\n  owner: String\n  comments: [Comment] @connection\n}\n\ntype Comment @model\n  @auth(rules: [\n    { allow: owner },\n    { allow: public, operations: [read] },\n    { allow: private, operations: [read] }\n  ]) {\n  id: ID\n  message: String\n  owner: String\n}\n```\n\nNow, we can create relationships between posts and comments. Let's test this out with the following operations:\n\n```graphql\nmutation createPost {\n  createPost(input: {\n    id: \"test-id-post-1\"\n    name: \"Post 1\"\n    location: \"Jamaica\"\n    description: \"Great vacation\"\n  }) {\n    id\n    name\n    description\n  }\n}\n\nmutation createComment {\n  createComment(input: {\n    postCommentsId: \"test-id-post-1\"\n    message: \"Great post!\"\n  }) {\n    id message\n  }\n}\n\nquery listPosts {\n  listPosts {\n    items {\n      id\n      name\n      description\n      location\n      comments {\n        items {\n          message\n          owner\n        }\n      }\n    }\n  }\n}\n```\n\nIf you'd like to read more about the `@auth` directive, check out the documentation [here](https://docs.amplify.aws/cli/graphql-transformer/directives#auth).\n\n## Local mocking\n\nTo mock the API, database, and storage locally, you can run the `mock` command:\n\n```sh\n$ amplify mock\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 Amplify project and all services\n\nIf you'd like to delete the entire project, you can run the `delete` command:\n\n```sh\n$ amplify delete\n```\n\n\u003c!-- ## Real-time --\u003e\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 real-time data coming in from the subscription, \u0026 update the state whenever a new piece of data comes in.\n\n```js\n// import the subscription\nimport { onCreateTalk as OnCreateTalk } from './graphql/subscriptions'\n\n// define the subscription in the class\nsubscription = {}\n\n// subscribe in componentDidMount\ncomponentDidMount() {\n  this.subscription = API.graphql(\n    graphqlOperation(OnCreateTalk)\n  ).subscribe({\n      next: (eventData) =\u003e {\n        console.log('eventData', eventData)\n        const talk = eventData.value.data.onCreateTalk\n        if (talk.clientId === CLIENT_ID) return\n        const talks = [ ...this.state.talks, talk ]\n        this.setState({ talks })\n      }\n  })\n}\n\n// unsubscribe in componentWillUnmount\ncomponentWillUnmount() {\n  this.subscription.unsubscribe()\n}\n``` --\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdabit3%2Famplify-photo-sharing-workshop","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdabit3%2Famplify-photo-sharing-workshop","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdabit3%2Famplify-photo-sharing-workshop/lists"}