Giter Site home page Giter Site logo

aws-amplify-workshop-web's Introduction

Building Web Applications with AWS Amplify

In this workshop we'll learn how to build cloud-enabled web applications with React & AWS Amplify.

Topics we'll be covering:

Getting Started - Creating the React Application

To get started, we first need to create a new React project & change into the new directory using the Create React App CLI.

npx create-react-app full-stack-aws

Now change into the new app directory & install the AWS Amplify & AWS Amplify React libraries:

cd full-stack-aws

npm install --save aws-amplify @aws-amplify/ui-react

# or

yarn add aws-amplify @aws-amplify/ui-react

Installing the CLI & Initializing a new AWS Amplify Project

Installing the CLI

Next, we'll install the AWS Amplify CLI:

npm install -g @aws-amplify/cli

Now we need to configure the CLI with our credentials.

If you'd like to see a video walkthrough of this configuration process, click here.

amplify configure

- Specify the AWS Region: us-east-1 || us-west-2 || eu-central-1
- Specify the username of the new IAM user: amplify-workshop-user
> In the AWS Console, click Next: Permissions, Next: Tags, Next: Review, & Create User to create the new IAM user. Then return to the command line & press Enter.
- Enter the access key of the newly created user:   
? accessKeyId: (<YOUR_ACCESS_KEY_ID>)  
? secretAccessKey: (<YOUR_SECRET_ACCESS_KEY>)
- Profile Name: amplify-workshop-user

Initializing A New Project

amplify init

- Enter a name for the project: fullstackaws
- Enter a name for the environment: dev
- Choose your default editor: Visual Studio Code (or your default editor)
- Please choose the type of app that youre building: javascript
- What javascript framework are you using: react
- Source Directory Path: src
- Distribution Directory Path: build
- Build Command: npm run-script build
- Start Command: npm run-script start
- Do you want to use an AWS profile? Y
- Please choose the profile you want to use: amplify-workshop-user (or your preferred profile)

The Amplify CLI has initialized a new project & you will see a new folder: amplify & a new file called aws-exports.js in the root directory. These files hold your project configuration.

To view the sus of the amplify project at any time, you can run the Amplify status command:

$ amplify status

To view the amplify project in the Amplify console at any time, run the console command:

$ amplify console

Adding Authentication

To add authentication, we can use the following command:

$ amplify add auth

? Do you want to use default authentication and security configuration? Default configuration 
? How do you want users to be able to sign in when using your Cognito User Pool? Username
? Do you want to configure advanced settings? No, I am done. 

Now, we'll run the push command and the cloud resources will be created in our AWS account.

amplify push

To view the new Cognito authentication service at any time after its creation, you can visit the Amplify Console or run the following command:

amplify console auth

Configuring the React applicaion

Now, our resources are created & we can start using them!

The 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.

To configure the app, open src/index.js and add the following code below the last import:

import Amplify from 'aws-amplify'
import config from './aws-exports'
Amplify.configure(config)

Now, our app is ready to start using our AWS services.

Using the withAuthenticator component

To add authentication, we'll go into src/App.js and first import the withAuthenticator HOC (Higher Order Component) from @aws-amplify/ui-react:

import { withAuthenticator } from '@aws-amplify/ui-react'

Next, we'll wrap our default export (the App component) with the withAuthenticator HOC:

export default withAuthenticator(App)

Now, 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 & sign in.

To view users that have been created in Cognito at any time, visit the Cognito dashboard by running amplify console auth.

Next, you can add easily a Sign Out button at any time by using the AmplifySignOut component:

import { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react'

// usage
<AmplifySignOut />

Accessing User Data

We can access the user's info now that they are signed in by calling Auth.currentAuthenticatedUser().

Let's update the component to show the user their profile information:

import { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react'
import { Auth } from 'aws-amplify'
import { useState, useEffect } from 'react'

function App() {
  const [user, setUser] = useState(null)
  useEffect(() => {
    checkUser()
  }, [])
  async function checkUser() {
    const user = await Auth.currentAuthenticatedUser()
    setUser(user)
  }
  if (!user) return null
  return (
    <div>
      <h1 className="text-3xl font-semibold tracking-wide mt-6">Profile</h1>
      <h3 className="font-medium text-gray-500 my-2">Username: {user.username}</h3>
      <p className="text-sm text-gray-500 mb-6">Email: {user.attributes.email}</p>
      <AmplifySignOut />
    </div>
  )
}

export default withAuthenticator(App)

Custom authentication strategies

The 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 & functions.

Let's look at how we might create our own authentication flow.

To 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, & phone number.

To do this, we could create some initial state for these values & create an event handler that we could attach to the form inputs:

// initial state
const [formState, setFormState] = useState({ username: '', password: '', email: '', phone_number: '' })

// event handler
function onChange(event) {
  setFormState({ ...formState, [event.target.name]: event.target.value })
}

// example of usage with input
<input
  name='username'
  placeholder='username'
  onChange={onChange}
/>

We'd also need to have a method that signs up & signs 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, & forgotPassword. This function return a promise so they need to be handled asynchronously.

// import the Auth component
import { Auth } from 'aws-amplify'

// Class method to sign up a user
async function signUp() {
  const { username, password, email, phone_number } = formState
  try {
    await Auth.signUp({ username, password, attributes: { email, phone_number }})
  } catch (err) {
    console.log('error signing up user...', err)
  }
}

Adding a GraphQL API

To add a GraphQL API, we can use the following command:

amplify add api

? Please select from one of the above mentioned services GraphQL
? Provide API name: fullstackaws
? Choose an authorization type for the API: API key
? Enter a description for the API key: public
? After how many days from now the API key should expire (1-365): 365
? Do you want to configure advanced settings for the GraphQL API: No
? Do you have an annotated GraphQL schema? N
? Choose a schema template: Single object with fields
? Do you want to edit the schema now? (Y/n) Y

When prompted, update the schema (located at full-stack-aws/amplify/backend/api/fullstackaws/schema.graphql) to the following:

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

Next, let's push the configuration to our account:

amplify push

? Are you sure you want to continue: Y
? Do you want to generate code for your newly created GraphQL API: Y
? Choose the code generation language target: JavaScript
? Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/**/*.js
? Do you want to generate/update all possible GraphQL operations: Y
? Enter maximum statement depth: 2

To view the new AWS AppSync API at any time after its creation, run amplify console api from the command line.

Adding mutations from within the AWS AppSync Console

Next, open the AWS AppSync console:

amplify console api

> Choose GraphQL

Next, click on Queries in the left hand menu.

Execute the following mutation to create a new pet in the API:

mutation createPet {
  createPet(input: {
    name: "Zeus"
    description: "Best dog in the western hemisphere"
  }) {
    id
  }
}

Now, let's query for the pet:

query listPets {
  listPets {
    items {
      id
      name
      description
    }
  }
}

We can even add search / filter capabilities when querying:

query listPets {
  listPets(filter: {
    description: {
      contains: "dog"
    }
  }) {
    items {
      id
      name
      description
    }
  }
}

Interacting with the GraphQL API from our client application - Querying for data

Now that the GraphQL API is created we can begin interacting with it!

The first thing we'll do is perform a query to fetch data from our API.

To do so, we need to define the query, execute the query, store the data in our state, then list the items in our UI.

// import the useState and useEffect hooks from React
import { useState, useEffect } from 'react'

// import the API category from Amplify library
import { API } from 'aws-amplify'

import { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react'

// import the GraphQL query (created by the CLI)
import { listPets } from './graphql/queries'

function App() {
  // define some state to hold the data returned from the API
  const [pets, setPets] = useState([])

  useEffect(() => {
    // create and invoke a function to fetch the data from the API
    fetchPets()
    async function fetchPets() {
      try {
        const pets = await API.graphql({
          query: listPets
        })
        console.log('pets:', pets)
        setPets(pets.data.listPets.items)
      } catch (err) {
        console.log('error fetching pets...', err)
      }
    }
  }, [])
  return (
    <div className="App">
      <h1>My Pet App</h1>
      {
        pets.map((pet, index) => (
          <div key={index}>
            <h3>{pet.name}</h3>
            <p>{pet.description}</p>
          </div>
        ))
      }
      <AmplifySignOut />
    </div>
  );
}

export default withAuthenticator(App)

Performing mutations

Now, let's look at how we can create mutations.

import { useState, useEffect } from 'react'
import { API } from 'aws-amplify'
import { withAuthenticator, AmplifySignOut } from '@aws-amplify/ui-react'
import { listPets } from './graphql/queries'

// import GraphQL mutation
import { createPet } from './graphql/mutations'

function App() {
  const [pets, setPets] = useState([])

  // create form state
  const [formState, setFormState] = useState({ name: '', description: '' })

  useEffect(() => {
    // create and invoke a function to fetch the data from the API
    fetchPets()
    async function fetchPets() {
      try {
        const pets = await API.graphql({
          query: listPets
        })
        console.log('pets:', pets)
        setPets(pets.data.listPets.items)
      } catch (err) {
        console.log('error fetching pets...', err)
      }
    }
  }, [])

  // change form state then user types into input
  function onChange(event) {
    setFormState({
      ...formState, [event.target.name]: event.target.value
    })
  }

  // create a function that updates the API as well as the form state
  async function createPetMutation() {
    const { name, description } = formState
    if (name === '') return
    let pet = { name }
    if (description !== '') {
      pet = { ...pet, description }
    }
    const updatedPetArray = [...pets, pet]
    setPets(updatedPetArray)
    try {
      await API.graphql({
        query: createPet,
        variables: { input: pet }
      })
      console.log('item created!')
    } catch (err) {
      console.log('error creating pet...', err)
    }
  }

  return (
    <div className="App">
      <h1>My Pet App</h1>
      <input
        name='name'
        onChange={onChange}
        value={formState.name}
      />
      <input
        name='description'
        onChange={onChange}
        value={formState.description}
      />
      <button onClick={createPetMutation}>Create Pet</button>
      {
        pets.map((pet, index) => (
          <div key={index}>
            <h3>{pet.name}</h3>
            <p>{pet.description}</p>
          </div>
        ))
      }
      <AmplifySignOut />
    </div>
  );
}

export default withAuthenticator(App)

GraphQL Subscriptions

Next, let's see how we can create a subscription to subscribe to changes of data in our API.

To do so, we need to define the subscription, listen for the subscription, & update the state whenever a new piece of data comes in through the subscription.

// define the subscription
const SubscribeToNewPets = `subscription {
  onCreatePet {
    id
    name
    description
  }
}`;

// subscribe in componentDidMount
API.graphql(
  graphqlOperation(SubscribeToNewPets)
).subscribe({
    next: (eventData) => {
      console.log('eventData', eventData)
      const pet = eventData.value.data.onCreatePet
      const pets = [
        ...this.state.pets.filter(p => {
          const val1 = p.name + p.description
          const val2 = pet.name + pet.description
          return val1 !== val2
        }),
        pet
      ]
      this.setState({ pets })
    }
});

Adding a REST API

To add a REST API, we can use the following command:

amplify add api

Answer the following questions

  • Please select from one of the above mentioned services REST
  • Provide a friendly name for your resource that will be used to label this category in the project: amplifyrestapi
  • Provide a path, e.g. /items /pets
  • Choose lambda source Create a new Lambda function
  • Provide a friendly name for your resource that will be used to label this category in the project: amplifyrestapilambda
  • Provide the Lambda function name: amplifyrestapilambda
  • Please select the function template you want to use: Serverless express function (Integration with Amazon API Gateway)
  • Do you want to edit the local lambda function now? Y

Update the existing `app.get('/pets') route with the following:

app.get('/pets', function(req, res) {
  // Add your code here
  // Return the API Gateway event and query string parameters for example
  const pets = [
    'Spike', 'Zeus', 'Butch'
  ]
  res.json({
    success: 'get call succeed!',
    url: req.url,
    pets
  });
});
  • Restrict API access Y
  • Who should have access? Authenticated users only
  • What kind of access do you want for Authenticated users read/write
  • Do you want to add another path? (y/N) N

Now the resources have been created & configured & we can push them to our account:

amplify push

Interacting with the new API

Now that the API is created we can start sending requests to it & interacting with it.

Let's request some data from the API:

import { API } from 'aws-amplify'

// create initial state
state = { pets: [] }

// fetch data at componentDidMount
componentDidMount() {
  this.getData()
}
getData = async() => {
  try {
    const data = await API.get('apif8f4b7fe', '/pets')
    this.setState({ pets: data.pets })
  } catch (err) {
    console.log('error fetching data..', err)
  }
}

// implement into render method
{
  this.state.pets.map((p, i) => (
    <p key={i}>{p}</p>
  ))
}

Fetching data from another API in a Lambda function.

Next, let's configure the REST API to add another endpoint that will fetch data from an external resource.

The first thing we need to do is install axios in our Lambda function folder.

Navigate to amplify/backend/function/<FUNCTION_NAME>/src and install axios:

yarn add axios

# or

npm install axios

Next, in amplify/backend/function/<FUNCTION_NAME>/src/app.js, let's add a new endpoint that will fetch a list of people from the Star Wars API.

// require axios
var axios = require('axios')

// add new /people endpoint
app.get('/people', function(req, res) {
  axios.get('https://swapi.co/api/people/')
    .then(response => {
      res.json({
        people: response.data.results,
        success: 'get call succeed!',
        url: req.url
      });
    })
    .catch(err => {
      res.json({
        error: 'error fetching data'
      });
    })
});

Now we can add a new function called getPeople that will call this API:

getPeople = async() => {
  try {
    const data = await API.get('amplifyrestlamdbaapi', '/people')
    this.setState({ people: data.people })
  } catch (err) {
    console.log('error fetching data..', err)
  }
}

Working with Storage

To add storage, we can use the following command:

amplify add storage

Answer the following questions

  • Please select from one of the below mentioned services Content (Images, audio, video, etc.)
  • Please provide a friendly name for your resource that will be used to label this category in the project: YOURAPINAME
  • Please provide bucket name: YOURUNIQUEBUCKETNAME
  • Who should have access: Auth users only
  • What kind of access do you want for Authenticated users read/write
amplify push

Now, storage is configured & ready to use.

What we've done above is created configured an Amazon S3 bucket that we can now start using for storing items.

For example, if we wanted to test it out we could store some text in a file like this:

import { Storage } from 'aws-amplify'

// create function to work with Storage
addToStorage = () => {
  Storage.put('javascript/MyReactComponent.js', `
    import React from 'react'
    const App = () => (
      <p>Hello World</p>
    )
    export default App
  `)
    .then (result => {
      console.log('result: ', result)
    })
    .catch(err => console.log('error: ', err));
}

// add click handler
<button onClick={this.addToStorage}>Add To Storage</button>

This would create a folder called javascript in our S3 bucket & store a file called MyReactComponent.js there with the code we specified in the second argument of Storage.put.

If we want to read everything from this folder, we can use Storage.list:

readFromStorage = () => {
  Storage.list('javascript/')
    .then(data => console.log('data from S3: ', data))
    .catch(err => console.log('error'))
}

If we only want to read the single file, we can use Storage.get:

readFromStorage = () => {
  Storage.get('javascript/MyReactComponent.js')
    .then(data => console.log('data from S3: ', data))
    .catch(err => console.log('error'))
}

If we wanted to pull down everything, we can use Storage.list:

readFromStorage = () => {
  Storage.list('')
    .then(data => console.log('data from S3: ', data))
    .catch(err => console.log('error'))
}

Working with images

Working with images is also easy:

class S3ImageUpload extends React.Component {
  onChange(e) {
      const file = e.target.files[0];
      Storage.put('example.png', file, {
          contentType: 'image/png'
      })
      .then (result => console.log(result))
      .catch(err => console.log(err));
  }

  render() {
      return (
          <input
              type="file" accept='image/png'
              onChange={(e) => this.onChange(e)}
          />
      )
  }
}

Hosting

To deploy & host your app on AWS, we can use the hosting category.

amplify add hosting
  • Select the environment setup: DEV (S3 only with HTTP)
  • hosting bucket name YOURBUCKETNAME
  • index doc for the website index.html
  • error doc for the website index.html

Now, everything is set up & we can publish it:

amplify publish

Adding Analytics

To add analytics, we can use the following command:

amplify add analytics

Next, we'll be prompted for the following:

? Provide your pinpoint resource name: amplifyanalytics
? Apps need authorization to send analytics events. Do you want to allow guest/unauthenticated users to send analytics events (recommended when getting started)? Y
? overwrite YOURFILEPATH-cloudformation-template.yml Y

Recording events

Now that the service has been created we can now begin recording events.

To record analytics events, we need to import the Analytics class from Amplify & then call Analytics.record:

import { Analytics } from 'aws-amplify'

state = {username: ''}

async componentDidMount() {
  try {
    const user = await Auth.currentAuthenticatedUser()
    this.setState({ username: user.username })
  } catch (err) {
    console.log('error getting user: ', err)
  }
}

recordEvent = () => {
  Analytics.record({
    name: 'My test event',
    attributes: {
      username: this.state.username
    }
  })
}

<button onClick={this.recordEvent}>Record Event</button>

Removing Services

If at any time, or at the end of this workshop, you would like to delete a service from your project & your account, you can do this by running the amplify remove command:

amplify remove auth

amplify push

If you are unsure of what services you have enabled at any time, you can run the amplify status command:

amplify status

amplify status will give you the list of resources that are currently enabled in your app.

aws-amplify-workshop-web's People

Contributors

dabit3 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

aws-amplify-workshop-web's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.