Giter Club home page Giter Club logo

wild-rydes-mobile's Introduction

AWS Mobile Loft - Introduction to AWS Mobile

🤖 Getting started

To get started, we will first create a new React application using the Create React App CLI.

If you do not already have Creeate React App installed, install it now with the following command:

npm install -g create-react-app

Creating the app

create-react-app react-aws-app

Running the app

First, change into the new directory of the app we just created.

cd react-aws-app

Next, run the following command to launch the app in the web browser:

npm start

🤖 Lesson 1 - Introduction to AWS Mobile Hub & the AWS Mobile CLI

Installing & configuring a new mobile hub project.

⚡ Installing the AWS Mobile CLI

npm i -g awsmobile-cli

⚡ Configuring the CLI

awsmobile configure

If you need to get an accessKeyId & secretAccessKey:

  1. Visit the IAM Console.
  2. Click Users in left hand menu.
  3. Click Add User.
  4. Give the user a name & choose programatic access as the access type & click next.
  5. Click Create Group.
  6. Give the group a name & choose Administrator Access as the access type & click Create Group.
  7. Click Next & click Create User.
  8. Copy the accessKeyId & secretAccessKey to the terminal to configure the CLI.

⚡ Creating a new Project

awsmobile init

After running the above command you will have a few options:

  • Choose default for source directory
  • Choose default for project's distribution directory
  • Choose default for build command
  • Choose default for project's start command
  • Give the project a name of AmplifyReact

Now that the project is successfully created, we can view it in the AWS Console by running the following command:

awsmobile console

🤖 Lesson 2 - Integrating AWS & AWS Amplify into your React application

In this section, we'll first integrate our AWS Mobile Hub project in with our newly created React application using the AWS Amplify library.

We'll also learn how to add a new service, Amazon Cognito, to our existing AWS Mobile Hub project using the CLI. Finally, we'll implement Authentication into the application using Amazon Cognito with AWS Amplify.

⚡ Configuring the project with Amplify & aws-exports.js

  1. Open src/index.js
  2. Add the following code below the last import statement
// src/index.js
import Amplify from 'aws-amplify'
import config from './aws-exports'
Amplify.configure(config)

⚡ Adding a new service - User Signin with Amazon Cognito

  1. Add the new User Signin functionality using the CLI
awsmobile user-signin enable
  1. Push the new configuration to the Mobile Hub Console
awsmobile push
  1. To view the console, run the following command:
awsmobile console

Now, in the list of Backend services, we see that User Signin is now enabled.

⚡ Implementing User-signup & User-signin using the withAuthenticator HOC

  1. Open src/App.js

  2. Import the withAuthenticator HOC from aws-amplify-react

// src/App.js

import { withAuthenticator } from 'aws-amplify-react'
  1. Wrap the App export with the withAuthenticator HOC
export default withAuthenticator(App)

⚡ Introduction to implementing hand-rolled Authentication

AWS Amplify Auth category has over 30 different methods available, including signUp, confirmSignUp, signIn, confirmSignIn, changePassword, forgotPassword & many many others. You can view the entire API here.

To manually sign up a new User with our existing Amazon Cognito configuration, we can call Auth.signUp, & must provide the following parameters:

  • username<string>
  • password<string>
  • attributes<object>
    • email<string>
    • phone_number<string>

We would call some method, passing in the above info to Auth.signUp. In React, it could look something like this:

import { Auth } from 'aws-amplify'

signUpUser = () => {
  const { username, password, email, phone_number } = this.state
  Auth.signUp({
    username, password, attributes: { email, phone_number }
  })
  .then(success => console.log('successfully signed up user!: ', success))
  .catch(err => console.log('error signing up user: ', err))
}

This Sign Up would trigger an MFA using the provided phone number.

To handle MFA on user sign up & sign in, we can use confirmSignUp & confirmSignIn.

To see how to build a custom UI using the Auth class, check out this section of the documentation.

🤖 Lesson 3 - Adding an AWS Lambda Function

In this section, we'll see how to add a new Lambda function to our application. We'll then learn how to make changes to the Lambda function & push the new changes to our Mobile Hub console.

⚡ Creating a new Lambda Function using the CLI

  1. Run the following command to create a new Lambda function:
awsmobile cloud-api enable -p
  1. Choose the following options:
  • Create a new API
  • API name: PetAPI
  • HTTP path name: /pets
  • Here, choose default Lambda function name by hitting enter on your keyboard
  • Add another HTTP path: n

⚡ Interacting with the Lambda function using AWS Amplify

  1. In src/App.js, add the following below the last import
// src/App.js
import { API } from 'aws-amplify'

let apiName = 'PetAPI';
let path = '/pets';
  1. In the App component add a new componentDidMount lifecycle method to log out the returned data from the API.
async componentDidMount() {
  const data = await API.get(apiName, path)
  console.log('data: ', data)
}

Now, we should be able to run the app and see some information passed back to us from the API.

To see what is going on here, open the following file: awsmobilejs/backend/cloud-api/PetAPI/app.js

Here, we can see that the Lamdba function is running an express server, handling various paths. If we look at the app.get('/pets/' path, we see that for right now it is returning res.json(req.apiGateway.event);

Let's update this to return an array of pets.

⚡ Updating the Lambda function

  1. Update the app.get('/pets/' path to the following:
app.get('/pets', function(req, res) {
  const pets = [
    'Buster', 'Mary', 'Spike', 'Pebbles'
  ]
  res.json({
    data: pets
  });
});
  1. Push the new code to Mobile Hub:
awsmobile push
  1. Rerun the app
npm start

⚡ Rendering the list of pets from the API in the UI

Next, we want to render the data being returned from the API. To do so, we'll create some state in the component to hold the data. Then, once the data is returned from the API, we'll reset the state, passing in the new data.

  1. Create state in the component
state = {
  pets: []
}
  1. Change componentDidMount to set the state when the data is returned.
async componentDidMount() {
  const data = await API.get(apiName, path)
  console.log('data: ', data)
  this.setState({
    pets: data.data
  })
}
  1. Finally, add the following code to your render method to display the list of pets in the UI:
{
  this.state.pets.map((pet, index) => (
    <h2 key={index}>{pet}</h2>
  ))
}

🤖 Lesson 4 - Adding Analytics with Amazon Pinpoint

Next, we'd like to add analytics to the app!

When we created the new Mobile Hub project, the initial configuration has Pinpoint enabled by default so we do not need to do anything add the service, we can just start using it.

The will be using the Analytics API from AWS Amplify to interact with Pinpoint & to log analytics.

Analytics can take the following arguments:

// 1. only the event name
Analytics.record({ name: 'Add to cart button clicked' })

// 2. event name & some attributes
Analytics.record({ name: 'Added socks to shopping cart', attributes: { username: 'amanda33' }})

// 3. event name, attributes, & metrics
Analytics.record({ name: 'Added socks to shopping cart', attributes: { username: 'amanda33' }, metrics: { time: '8:33pm ET' } })

⚡ Recording an Analytics event

Let's create a button that records an event.

In src/App.js, import the Analytics module:

// src/App.js
import { Analytics } from 'aws-amplify'

Next, add the following method to the class:

addToCart = () => {
  console.log('Simulating adding item to cart.')
  Analytics.record('Item added to cart!')
}

Now, create a button in the render method & attach the method to the onClick function of the button:

<button onClick={this.addToCart}>Add To Cart</button>

Now, click on the button a couple of times. We should now be able to see the data from this event logged into our Pinpoint console.

⚡ Viewing Analytics events & data in the Pinpoint console

Next, let's view the Pinpoint console to see the events we've logged so far.

  1. Open the AWS Mobile Hub console
awsmobile console
  1. Click Analytics in the top right hand corner

  2. Click on Events in the left menu

🤖 Lesson 5 - Adding GraphQL with AWS AppSync

Next, we would like to add a AWS AppSync GraphQL API to the application.

⚡ Creating the API

We can create the new API from the command line:

awsmobile appsync enable -p

Next, choose API_KEY as the auth type.

Now, push the new configuration to AWS Mobile Hub:

awsmobile push

Now that the API has been created, let's go into the AWS console to update the configuration.

Visit the AWS AppSync console at https://console.aws.amazon.com/appsync/.

Fromt here, click on the AmplifyReact API to open it in the console.

⚡ Configuring the API

Now we need to update the existing schema to our new schema.

Click on Schema in the left hand menu to open the schema editor.

Here, delete the existing schema and add the following, then click Save Schema:

type Pet {
  id: ID!
  name: String!
}

type Query {
  fetchPet(id: ID!): Pet
}

Next, click on the Create Resources button in the top right corner.

When asked to Define or select a type, choose Use existing type, and then choose the Pet type. Then scroll down & click Create.

Once the resources have finished being created, we can start executing mutations against the API.

In the left hand menu, click on Queries, & add the following mutation into the query editor, then click the orange play button:

mutation create {
  createPet(input:{
    name: "Spike"
  }) {
    id
  }
}

Feel free to create as many Pets as you would like, as we will be querying for this data in just a moment.

If you would like to query the data to make sure everything is working properly, try using this query in the query editor:

query list {
  listPets {
    items {
      id
      name
    }
  }
}

⚡ Connecting the React application to the AWS AppSync API

Now that the API is created & working properly, let's go ahead and query for data from the client & show it in the UI.

In src/App.js, let's go ahead and import API & graphqlOperation from 'aws-amplify':

// src/App.js
import { API, graphqlOperation } from 'aws-amplify'

Next, we'll define our query:

const ListPets = `
  query {
    listPets {
      items {
        id
        name
      }
    }
  }
`

Now, in the class, we'll define some state, and set a pets property equal to an empty array for now:

state = { pets: [] }

Now that we have some initial state, we'll call the AppSync API to fetch the data within the componentDidMount lifecycle hook:

async componentDidMount() {
  const pets = await API.graphql(graphqlOperation(ListPets))
  console.log('pets: ', pets) // optional, if you would like to view the shape of the data
  this.setState({ pets: pets.data.listPets.items })
}

In the render method, we can now display the data to the UI:

{
  this.state.pets.map((pet, index) => (
    <h2 key={index}>{pet.name}</h2>
  ))
}

The final component code for querying the AWS AppSync API should look like this:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

import { API, graphqlOperation } from 'aws-amplify'

const ListPets = `
  query {
    listPets {
      items {
        id
        name
      }
    }
  }
`

class App extends Component {
  state = { pets: [] }
  async componentDidMount() {
    const pets = await API.graphql(graphqlOperation(ListPets))
    console.log('pets: ', pets)
    this.setState({ pets: pets.data.listPets.items })
  }
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
        {
          this.state.pets.map((pet, index) => (
            <h2 key={index}>{pet.name}</h2>
          ))
        }
      </div>
    );
  }
}

export default App;

⚡ Creating a mutation

First, we need to create a mutation:

const CreatePet = `
  mutation($name: String!) {
    createPet(input: {
      name: $name
    }) {
      id
    }
  }
`

Now we need to store some state in the class to keep up with user input:

state = { name: '', pets: [] }

Next, we'll create an onChange class method that will handle user input, storing it in the state:

onChange = (e) => { this.setState({ name: e.target.value }) }

Now, we'll create a class method that will call the API to create the mutation:

createPet = () => {
  const pet = { name: this.state.name }
  API.graphql(graphqlOperation(CreatePet, pet))
  const pets = [...this.state.pets, pet]
  this.setState({ pets, name: '' })
}

Finally, in the render method we'll create a button & input form to work with the new methods:

<input onChange={this.onChange} placeholder='Pet name' />
<button onClick={this.createPet}>Create Pet</button>

Deleting resources

Throughout this tutorial, we've created a few resources in your AWS account. If you are interested in removing any resources you will not be using in the future, here are the resources you should delete around this project:

  1. In Mobile hub, delete the new project we created here
  2. In Amazon s3, delete the bucket associated with this project
  3. In AWS AppSync, delete the API we created along with this project

wild-rydes-mobile's People

Contributors

adrianhall avatar dabit3 avatar khalildh avatar promediacorp avatar sojungko 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

Watchers

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

wild-rydes-mobile's Issues

Error in README

The command awsmobile publish -c -n -f is incorrect as awsmobile publish does not seem to recognize the -n flag.

awsmobile publish -c -f works fine.

In React-Native Branch, we need to specify where we add the `Auth.currentAuthenticatedUser`

@@ -159,7 +159,7 @@ confirmsignIn = () => {

Once the user is logged in, we want to be able to check AsyncStorage to see if the user is still available, and if so autmoatically log them in.

-To do so, we can call Auth.currentAuthenticatedUser, and if this call returns successfully we can log them in automratically:
+To do so, we can call Auth.currentAuthenticatedUser in src/auth/Home.js, and if this call returns successfully we can log them in automratically:

// import Auth from amplify in imports

"filter" error

Okay, so react-native branch, when you get sign-in finished and sign in, it directs to MainApp.js, where there's an error that pops up with filter being undefined or something. In the workshop, we commented out the hasAPI function and moved on. Inspecting awsconfig.js for aws_cloud_logic_custom, which filter is being run on, reveals that at this point because awsmobile cloud-api enable --prompt hasn't been run yet, there is no aws_cloud_logic_custom field.

Related: the getData and onPress methods are on the MainApp component, not in the home/HailRide component, which doesn't exist in the react-native project. Also, the button is written with onClick, rather than onPress.

Which gets us pretty far, but I still get:

MainApp.js:101 Error: Request failed with status code 500
at e.exports (createError.js:16)
at e.exports (settle.js:18)
at XMLHttpRequest.f.(/anonymous function) (http://wildrydesmobilenomfa-hosting-mobilehub-1749570465.s3-website.us-east-1.amazonaws.com/static/js/main.b3c7b4f2.js:1:374694)

  (anonymous) @ MainApp.js:101
  r @ runtime.js:62
  (anonymous) @ runtime.js:296
  e.(anonymous function) @ runtime.js:114
  r @ main.b3c7b4f2.js:76606
  (anonymous) @ main.b3c7b4f2.js:76606
  Promise.then (async)    
  r @ main.b3c7b4f2.js:76606
  (anonymous) @ main.b3c7b4f2.js:76606
  (anonymous) @ main.b3c7b4f2.js:76606
  e @ main.b3c7b4f2.js:76631
  onClick @ MainApp.js:158
  i @ react-dom.production.min.js:15
  invokeGuardedCallback @ react-dom.production.min.js:16
  invokeGuardedCallbackAndCatchFirstError @ react-dom.production.min.js:16
  l @ react-dom.production.min.js:20
  f @ react-dom.production.min.js:22
  m @ react-dom.production.min.js:22
  d @ react-dom.production.min.js:21
  g @ react-dom.production.min.js:24
  v @ react-dom.production.min.js:24
  Le @ react-dom.production.min.js:82
  batchedUpdates @ react-dom.production.min.js:186
  Q @ react-dom.production.min.js:42
  Ke @ react-dom.production.min.js:84
  interactiveUpdates @ react-dom.production.min.js:187
  ze @ react-dom.production.min.js:83

I'd love to help further, I haven't debugged async code all that much though, and it will certainly be faster for someone with more experience to look through the onPress (onClick) method and see why it's catching. I think I'd done everything else right. Here's my repo, including modification to not use MFA, though you have to include a phone number ... because schema? Lot going on right then. You can get up and running this way if you don't have a phone to receive the MFA code, though.

https://github.com/Twitchkidd/wild-rydes-react-native-no-mfa

Oh also just noting, currently country code (+1) must be included for a valid phone number.

Thanks so much for throwing Mobile Week guys! It was a blast!

API.get throws CORS header ‘Access-Control-Allow-Origin’ missing

I tried configuring cloud-api. but I am getting following CORS errors.

when I try API.get() method.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxxx.execute-api.eu-west-1.amazonaws.com/Development/pet. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

any idea how to fix this ?

backend awsmobile project unknown

I get this error when following the beginning section of the intro-to-aws-mobile branch.

backend awsmobile project unknown

I followed the steps exactly and this is what it produces. I should also mention that I wasnt given the opportunity to name the project in the init step, it skipped over it and named it as you see below.

spadg@DESKTOP-DADGJRU MINGW64 ~/WebDevelopment/00-Projects/Local/Learn AWS
$ create-react-app aws-mobile-react

Creating a new React app in C:\Users\spadg\WebDevelopment\00-Projects\Local\Learn AWS\aws-mobile-react.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...


> [email protected] postinstall C:\Users\spadg\WebDevelopment\00-Projects\Local\Learn AWS\aws-mobile-react\node_modules\uglifyjs-webpack-plugin
> node lib/post_install.js

+ [email protected]
+ [email protected]
+ [email protected]
added 1318 packages from 810 contributors and audited 14279 packages in 27.409s
found 0 vulnerabilities


Success! Created aws-mobile-react at C:\Users\spadg\WebDevelopment\00-Projects\Local\Learn AWS\aws-mobile-react
Inside that directory, you can run several commands:

  npm start
    Starts the development server.

  npm run build
    Bundles the app into static files for production.

  npm test
    Starts the test runner.

  npm run eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd aws-mobile-react
  npm start

Happy hacking!

spadg@DESKTOP-DADGJRU MINGW64 ~/WebDevelopment/00-Projects/Local/Learn AWS
$ cd aws-mobile-react/

spadg@DESKTOP-DADGJRU MINGW64 ~/WebDevelopment/00-Projects/Local/Learn AWS/aws-mobile-react
$ awsmobile configure

configure aws
? accessKeyId:  my-access-key-went-here
? secretAccessKey:  my-secret-access-key-went-here
? region:  us-west-1


spadg@DESKTOP-DADGJRU MINGW64 ~/WebDevelopment/00-Projects/Local/Learn AWS/aws-mobile-react
$ awsmobile init

Please tell us about your project:
? Where is your project's source directory:  src
? Where is your project's distribution directory that stores build artifacts:  build
? What is your project's build command:  npm.cmd run-script build
? What is your project's start command for local test run:  npm.cmd run-script start

? What awsmobile project name would you like to use:  (aws-mobile-react-2018-07-21-18-33-10)

spadg@DESKTOP-DADGJRU MINGW64 ~/WebDevelopment/00-Projects/Local/Learn AWS/aws-mobile-react
$ awsmobile console

backend awsmobile project unknown

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.