Skip to main content

Command Palette

Search for a command to run...

Build a Simple Productivity App with AWS Amplify and React

Updated
7 min read
Build a Simple Productivity App with AWS Amplify  and React
T

Hello! I am a passionate cloud enthusiast who is constantly seeking to expand my knowledge of emerging technologies and techniques. My primary focus revolves around AWS, Terraform, Azure, and Docker. Through my journey, I aim to explore and understand the intricacies of these platforms while embracing their potential to drive innovation and efficiency in cloud computing. As a result, I am excited to share my insights and experiences through informative blog posts, providing valuable resources to fellow cloud enthusiasts and those eager to learn more about these technologies. Join me on this exciting adventure as we navigate the ever-evolving world of cloud computing together!


Introduction

Greetings, tech enthusiasts and fellow developers!

As an aspiring developer, this is my first blog and pretty much excited to share my learnings, challenges, and Building a simple productivity app using AWS Amplify and ReactJs.

I hope to inspire others to pursue their passion for tech and embrace the world of possibilities it offers.

Technology

  1. AWS Amplify

  2. AWS AppSync

  3. AWS S3

  4. AWS DynamoDB

  5. AWS Cognito

  6. React js

  7. GraphQL

Architecture Diagram

Prerequisite

  • AWS Account

  • npm installed

  • AWS&Amplify cli

project initialization

Creating a React app is the crucial initial step in the project. To do this, open the terminal and paste the above code, which will set up the React app in our system. This sets the foundation for building the application and allows us to begin working with React components, manage the state, and design the user interface.

npm create-react-app Contactplus
cd Contactplus
npm start

Amplify configure

First, we need to install Amplify-cli to setup Amplify Resources in our system by using the above command:

npm i -g @aws-amplify/cli

At the project directory, run the above Command:

amplify configure

After Following the command, now you can able access aws Account to set up your project in the cloud theses includes:

  • Choose Region

  • Set the username for the new IAM user

  • Redirect to AWS console to check and set permissions, get Access key ID and secret access key

And after creating a new IAM user, now we can deploy our application in the cloud by using the above command:

amplify init

At this point we can see our app in aws console:

Add Cognito(Auth)

  • create Account

  • Sign in

  • Sign out

Execute the above command to add authentication function to add authentication functions to our application:

amplify add auth

At this stage, I have opted for email as the user registration method for the account. Any changes or updates made to the registration process can be modified in Cognito through your AWS console. Once you've made the desired changes, running the above command will save and deploy those changes to the cloud, ensuring that the updated registration process is active and accessible for users. This way, we can efficiently manage user authentication and account registration in our React app using AWS Cognito.

amplify init

The amplify directory contains all the backend resources, configurations, and authentication settings for your app.

The aws-exports.js file, located within the amplify directory, contains the configuration information needed by your application to interact with the AWS services you've set up using Amplify. It includes details such as AWS service endpoints, identity pool IDs, and user pool IDs, among other configurations.

Install the necessary packages:

npm i aws-amplify @aws-amplify/ui-react

To see the status:

amplify status

add import and add amplify auth components in your App.js File:

import { Amplify } from 'aws-amplify';
import { Authenticator} from '@aws-amplify/ui-react';
import { useAuthenticator } from '@aws-amplify/ui-react';
import awsExports from './aws-exports';

Amplify.configure(awsExports);
function App() {
  return (
    <Authenticator loginMechanisms={['email']}>
      {({ signOut, user }) => (
        <div>
          {/* ... (SiteNav and other components) */}
          <Routes>
            {/* ... (Routes for Homepage and Contacts) */}
          </Routes>
          {/* ... (SiteFooter) */}
        </div>
      )}
    </Authenticator>
  );
}
export default App;

With the help of AWS Amplify, adding authentication capabilities to your application is incredibly fast and straightforward. Amplify provides a powerful set of pre-built UI components, such as Authenticator, which handles user sign-up, sign-in, and sign-out flows, among others. By simply integrating these components into your React application and configuring a few settings, you can enable secure authentication with popular providers like email, social media, or identity providers.

Use DynamoDB and GraphQL for API

by adding API to our application you can run the above command:

amplify add api

In this step, I have chosen to use the GraphQL API with a schema template consisting of a single object and its fields. Amplify automatically generates default authorization settings for this schema. Below is the sample schema generated by Amplify:

type Todo @model {
  id: ID!
  name: String!
  description: String
}

so for my application, I want to change the schema according to my application so I modified the model as follows:

type Contact @model (rules: [{ allow: owner }]) {
  id: ID!
  name: String!
  email: String!
  Phone: String!
  Department: String!
  profilePicture: S3Object
}

After you finish editing the GraphQL schema using the AWS Amplify CLI and push the changes to AWS, the newly generated GraphQL operations (mutations, queries, and subscriptions) will be available in your src/graphql folder.

When you push the changes, AWS Amplify automatically generates and deploys the necessary GraphQL resources, including the API, database tables, and GraphQL schema. The new GraphQL schema and the generated operations are then made available in your React application, and you can import and use them in your code to interact with the backend API.

function to get listContacts and createContact:

import { API, graphqlOperation } from "aws-amplify";
import { createContact } from "../../graphql/mutations";
import { listContacts } from "../../graphql/queries";

function Contacts() {
  // ... (Other state and functions)

  const getContacts = async () => {
    try {
      const { data: { listContacts: { items } } } = await API.graphql(graphqlOperation(listContacts));
      setContacts(items);
    } catch (err) {
      console.log('error', err);
    }
  };

  const addNewContact = async () => {
    const { name, email, Phone, Department } = contactData;

    // ... (File upload to S3)

    const newContact = {
      id: uuidv4(),
      name,
      email,
      Phone,
      profilePicture: key,
      Department,
    };

    try {
      await API.graphql(graphqlOperation(createContact, { input: newContact }));
      setContacts([...contacts, newContact]);
      setContactData({
        name: "",
        email: "",
        Phone: "",
        Department: "",
      });
      setProfilePicture([]);
    } catch (err) {
      console.log('error', err);
    }
  };

  // ... (Other JSX and components)

}

export default Contacts;

my application at this moment

login page

registration page

Homepage

Storage for the images on S3

To use S3 for storing the application's images we run the following command:

amplify add storage

then choose the content type to store, set the bucket name, who can access it,the permissions of the auth users, and whether to use a lambda trigger then finally run amplify push the resources to the cloud

then type amplify status :

you can see what the things created in the cloud

using AWS Amplify storage class to get access URLS of the image.

#It contains only s3 components 

import Amplify, { Storage } from 'aws-amplify';

// Configure Amplify with your AWS settings
Amplify.configure({
  Auth: {
    // Configure Auth settings as needed
  },
  Storage: {
    // Configure Storage settings with your AWS S3 bucket information
    bucket: 'your-bucket-name',
    region: 'us-east-1', // Replace with your region
    identityPoolId: 'your-identity-pool-id', // Replace with your Identity Pool ID
  },
});

// Function to upload a profile picture to AWS S3 using Amplify Storage
const uploadProfilePic = async (profilePicFile) => {
  try {
    // Upload pic to S3
    const { key } = await Storage.put(`${Date.now()}.png`, profilePicFile, { contentType: 'image/png' });

    // Retrieve the public URL of the uploaded file
    const profilePicURL = await Storage.get(key);

    console.log('Profile picture uploaded successfully. URL:', profilePicURL);
  } catch (err) {
    console.log('Error uploading profile picture:', err);
  }
};

// Usage example
const profilePicFile = /* Replace with the actual profile picture file */;

uploadProfilePic(profilePicFile);

upload images in the contacts we can see it in our S3 bucket

In our DynamoDB we can see the details

Contact details of the person

Add New Contact

Deploy and Host the app

You can view our app source code in the above link

Github link -> Amplify_hashnode hackathon

guys, we are at the end of our blog and this is my first blog, I hope it helps something about AWS Amplify, and I hope to receive your support and suggestions

yes, it's done. this is just a simple demo application for applying Aws Amplify

to build a web application with ReactJS all the work is done very quickly

In the future we update adding more features to the app, the knowledge in this article is very limited and AWS Amplify does more than that

Resources

#AWSAmplify #AWSAmplifyHackathon @AWSAmplify @hashnode