Today we will create an app called Adopt a Pet, where you can find your next best friend.
It will looking something like this:
Access the Amplify Sandbox at https://sandbox.amplifyapp.com/ to ceate your data model.
npx create-react-app@latest adopt-a-pet
cd adopt-a-pet
curl -sL https://aws-amplify.github.io/amplify-cli/install | bash && $SHELL
amplify pull --sandboxId <sandboxId>
Amplify created a GraphQL schema for our data model at amplify/backend/api/amplifyDatasource/schema.graphql
:
type Owner @model @auth(rules: [{allow: public}]) {
id: ID!
name: String!
email: AWSEmail!
}
enum PetType {
CAT
DOG
}
type Pet @model @auth(rules: [{allow: public}]) {
id: ID!
name: String!
description: String
photo: AWSURL!
petType: PetType!
owner: Owner @hasOne
}
Modify src/App.js
to create a new Pet:
import { DataStore } from '@aws-amplify/datastore';
import { Pet, PetType } from './models';
function App() {
const addPet = async() => {
const newPet = await DataStore.save(new Pet({
"name": prompt('Name'),
"photo": prompt('Photo'),
"petType": PetType.DOG,
}));
console.log(newPet);
}
return (
<div className="App">
<button onClick={addPet}>Add Pet</button>
</div>
);
}
export default App;
We will use React's useEffect
to fetch Pets when loading the App:
import { DataStore } from '@aws-amplify/datastore';
import { useEffect } from 'react';
import { Pet, PetType } from './models';
function App() {
useEffect(() => {
const getPets = async() => {
const models = await DataStore.query(Pet);
console.log(models);
}
getPets()
}, []);
...
}
export default App;
npm install @aws-amplify/ui-react
Configure Amplify on src/index.js
:
import Amplify from 'aws-amplify';
import "@aws-amplify/ui-react/styles.css";
import {AmplifyProvider} from "@aws-amplify/ui-react";
import awsconfig from './aws-exports';
Amplify.configure(awsconfig);
Add authentication:
amplify add auth
Push changes to the cloud:
amplify push