Reader small image

You're reading from  Rapid Application Development with AWS Amplify

Product typeBook
Published inJul 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781800207233
Edition1st Edition
Languages
Concepts
Right arrow
Author (1)
Adrian Leung
Adrian Leung
author image
Adrian Leung

Adrian Leung is a full-stack cloud native engineer and Agile Transformation Coach with a deep understanding of Business and Organisational Agilities. His background has led him to coach many enterprises in digital transformation with Design Thinking and Agile as well as enterprise scalable cloud-native solution architectures to deliver real value to their customers. Adrian earned a degree in Applied Information Technology from The University of Newcastle, Australia in 2007. His work history includes helping many enterprises in Hong Kong with their digital transformation journey. He is currently the Founder of Adventvr that is building amazing products and espousing the benefits of serverless systems whenever he has the chance.
Read more about Adrian Leung

Right arrow

Chapter 6: Uploading and Sharing Photos with Amplify Storage

In this chapter, we will continue with what we built in Chapter 5, Creating a Blog Post with Amplify GraphQL, by adding the ability for users to upload and share photos to their blog. AWS Amplify comes with quite a few pre-built UI components that are ready to use. In this chapter, we will learn how to utilize the Photo Picker and Image components for our tutorial. Photo sharing is very common on the internet these days – it's a way to show people what you care about, not only with text but images, which gives people an idea of your life. The entire image upload and display mechanism can be quite complex for many, especially for those who are not familiar with backend technologies. AWS Amplify handles this for you behind the scenes – all you need to do is plug and play with several Amplify UI components.

In this chapter, we will cover the following topics:

  • Adding the React Photo Picker UI component...

Technical requirements

To follow along with this chapter, you will need to have completed the exercises in all the previous chapters so that you can start adding photos to blog posts. You can download the file for this chapter from the following link: https://github.com/PacktPublishing/Rapid-Application-Development-with-AWS-Amplify/tree/master/ch6.

We will need to change the data model to the following to accommodate the user uploading image alongside the actual blog post. Once we've done this, we'll need to call the amplify push command to push the new changes to the cloud:

type Post @model @key(fields: ["title"]) {
  id: ID!
  title: String!
  content: String!
  image: String
}

To upload photos to the Amplify Storage backend, we will need to call the amplify add storage command in a Terminal. This will add Amplify Storage to the cloud's backend:

amplify add storage
? Please select from one of the below mentioned...

Adding the React Photo Picker UI component and Amplify Storage with ReactJS

In this section, we will learn how to add the Photo Picker UI component to the app, as well as the code that lets the user add a photo to the app through Amplify Storage. This will allow other users to see the photo through the app. Normally, we would need to write a lot of frontend and backend code to achieve this, but in this section, I will show you how to code in a minimal way. Let's get started:

  1. Let's open the App.css file and add the following CSS code so that we can style the Amplify S3 Image UI component at the bottom of the CSS file:
    amplify-s3-image {
      --width: 400px;
    }
  2. Open the App.tsx file and add the following code to it:
    import React, { useEffect, useState, SetStateAction } from "react";
    import "./App.css";
    import Amplify, { API, graphqlOperation, Storage } from "aws-amplify";
    import * as mutations from "./graphql/mutations"...

Sharing an image with text as a blog post with ReactJS

In this section, we will create a blog post with the code that we created in the previous section. Imagine that someone who has visited your website has signed up and logged in as a user and then thinks of something worth sharing. To do this, they must create a blog post. In this section, we will show you how the user will pick an image and then add a title and content, as well as click the Create button to ensure the functionalities are working perfectly. Let's get started:

  1. First, let's call the yarn start command in a Terminal to run the app. Try to create a new post by uploading a photo, fill in the title and content fields, and then click the Create button:

    Figure 6.1 – Uploading a photo during post creation

  2. You should be able to scroll down to the bottom of the page to check out the newly created post, as shown here:

Figure 6.2 – Newly created post with an image

...

Listing all the blog posts with real-time updates with ReactJS

In this section, we will learn how to use subscriptions in our app to listen to certain events such as post creation, post update, and post delete. As soon as we call the backend through the GraphQL API to perform a task, such as creating a post, the subscribers of the onCreatePost event will get notified. The same will happen for post update and deletion. Let's get started:

  1. Add the following code anywhere before the return section of the App.tsx file:
      const createSubscription: any = API.graphql(
        graphqlOperation(subscriptions.onCreatePost)
      );
      createSubscription.subscribe({
        next: (postData: any) => {
          console.log("onCreatePost", postData);
          fetchPosts();
        },
      });
      const updateSubscription: any = API...

Adding the Photo Picker component with Amplify Storage with Expo and React Native

In this section, we will add the Photo Picker component to our Expo and React Native apps to let the user upload photos to Amplify Storage (an S3 Bucket). The steps will be similar between Expo and React Native, but the component will be slightly different.

To let the user upload their image to Amplify Storage, we need to add the image picker library to the project:

  1. For the Expo app, install the specific image picker library that is developed by Expo called expo-image-picker by running the following command:
    expo install expo-image-picker
  2. For the React Native app, install the community-made image called react-native-image-picker by running the following two commands:
    yarn add react-native-image-picker
    npx pod-install
  3. Once you have installed the image picker for your React Native project, recompile the project with the yarn ios and yarn android commands to see if it works.
  4. If you try...

Sharing an image with text as a blog post with React Native and Expo

In this section, we will learn how to let users upload images as part of a blog post to an S3 Bucket via the built-in Amplify Storage service. We will look at both the Expo and React Native projects, and point out the differences between the two. Open the App.tsx file in your Expo or React Native project and follow these steps:

  1. First, we must import the required libraries; that is, the React and React Native UI components:
    import React, { useEffect, useState, SetStateAction } from "react";
    import {
      View,
      Text,
      SafeAreaView,
      ScrollView,
      Image,
      TextInput
    } from "react-native";
    import { StatusBar } from 'expo-status-bar';
    import styles from "./AppStyles";
    import Amplify, { Auth, API, graphqlOperation, Storage } from "aws-amplify";
    import * as mutations from "./src/graphql/mutations"...

Listing all the blog posts with real-time updates with React Native and Expo

In this section, we will learn how to add a real-time subscription to the app, which is important if you are creating an app where you want to let users subscribe to any updates that they are interested in, such as receiving a notification about a blog post or a new article for a website or app. Let's get started:

  1. Open the App.tsx file again and add the following code anywhere within the main App function code block:
      const createSubscription: any = API.graphql(
        graphqlOperation(subscriptions.onCreatePost)
      );
      createSubscription.subscribe({
        next: (postData: any) => {
          console.log("onCreatePost", postData);
          fetchPosts();
        },
      });
      const updateSubscription: any = API.graphql(
      ...

Summary

In this chapter, we have learned how to create an image blog post with real-time subscriptions for both web apps and mobile apps with React, Expo, and React Native. We also learned how to add the pre-built Photo Picker component from the Amplify library to the app, how to create a feature for uploading the photo to Amplify Storage, and how to list all the blog posts for the users in real time. These features allow modern websites and apps to update without the user having to either refresh their website manually or pull to refresh their app on their smart phone. This improves the user experience in general. The code bases between ReactJS, React Native, and Expo are very similar, which means you can share most of the code between these projects and reuse it.

In the next chapter, we will learn how to create an Amplify DevOps pipeline, which can deploy the ReactJS code to Amplify Hosting automatically, whenever we submit new code to the repository.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Rapid Application Development with AWS Amplify
Published in: Jul 2021Publisher: PacktISBN-13: 9781800207233
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Adrian Leung

Adrian Leung is a full-stack cloud native engineer and Agile Transformation Coach with a deep understanding of Business and Organisational Agilities. His background has led him to coach many enterprises in digital transformation with Design Thinking and Agile as well as enterprise scalable cloud-native solution architectures to deliver real value to their customers. Adrian earned a degree in Applied Information Technology from The University of Newcastle, Australia in 2007. His work history includes helping many enterprises in Hong Kong with their digital transformation journey. He is currently the Founder of Adventvr that is building amazing products and espousing the benefits of serverless systems whenever he has the chance.
Read more about Adrian Leung