Hey there, fellow devs! π
2023's here and with it comes even more potent AWS tooling! Today, we'll chat about AWS Amplify, a superhero tool for frontend and mobile devs. This bad boy makes crafting cloud-enabled apps feel like sipping your favorite latte β. And its Datastore API? Pure magic - no need to break a sweat over offline or online data scenarios.
Hang tight as we roll out a spiffy real-time message board using AWS Amplify and React. Buckle up! π’
π Setting Up the Project
Alrighty, first things first. Let's scaffold a new React project.
npx create-react-app amplify-datastore --use-npm
cd amplify-datastore
npx amplify-app@latest
Got that up? Sweet! π Now, let's twiddle with the GraphQL schema in amplify/backend/api/<project-name>/schema.graphql
. Shape it up to craft our Message data model.
type Message @model {
id: ID!
title: String!
color: String
createdAt: String
}
Before we dive into our app's UI, let's install some UI component dependencies. Oh, and of course, Amplify's core and datastore.
yarn add antd react-color @aws-amplify/core @aws-amplify/datastore
Now, let's churn out the models for our app:
npm run amplify-modelgen
Boom! Models ready. π To initialize our Amplify project in the wild, vast cloud:
amplify init
A bit more setup (like naming our environment), then we'll deploy with:
amplify push
When prompted about generating GraphQL code, since we're diving deep into the Datastore API, give a confident "no"!
π Building the App
Backend all set and shiny? Perfect! Let's roll up our sleeves and sculpt the frontend. Open up src/index.js
and make the necessary imports.
import Amplify from "@aws-amplify/core";
import config from "./aws-exports";
import "./index.css";
Good going! Now, let's bring in the ant design styling, Amplify, and the CLI-generated configuration from aws-exports
. Initialize Amplify with Amplify.configure(config)
. π
Onto App.js
. Wipe it clean - let's start fresh. Copy-paste the code below to breathe life into our real-time message board!
import React, { useState, useEffect } from "react";
import { SketchPicker } from "react-color";
import { Input, Button } from "antd";
import { DataStore } from "@aws-amplify/datastore";
import { Message } from "./models";
const initialState = { color: "#000000", title: "" };
function App() {
const [formState, updateFormState] = useState(initialState);
const [messages, updateMessages] = useState([]);
const [showPicker, updateShowPicker] = useState(false);
useEffect(() => {
fetchMessages();
const subscription = DataStore.observe(Message).subscribe(() =>
fetchMessages()
);
return () => subscription.unsubscribe();
}, []);
function onChange(e) {
if (e.hex) {
updateFormState({ ...formState, color: e.hex });
} else {
updateFormState({ ...formState, title: e.target.value });
}
}
async function fetchMessages() {
const messages = await DataStore.query(Message);
updateMessages(messages);
}
async function createMessage() {
if (!formState.title) return;
await DataStore.save(new Message({ ...formState }));
updateFormState(initialState);
}
return (
<div style={container}>
<h1 style={heading}>Real-Time Message Board</h1>
<Input
onChange={onChange}
name="title"
placeholder="Message title"
value={formState.title}
style={input}
/>
<div>
<Button onClick={() => updateShowPicker(!showPicker)} style={button}>
Toggle Color Picker
</Button>
<p>
Color:{" "}
<span style={{ fontWeight: "bold", color: formState.color }}>
{formState.color}
</span>
</p>
</div>
{showPicker && (
<SketchPicker color={formState.color} onChange={onChange} />
)}
<Button type="primary" onClick={createMessage}>
Create Message
</Button>
{messages.map((message) => (
<div
key={message.id}
style={{ ...messageStyle, backgroundColor: message.color }}
>
<div style={messageBg}>
<p style={messageTitle}>{message.title}</p>
</div>
</div>
))}
</div>
);
}
const container = { width: "100%", padding: 40, maxWidth: 900 };
const input = { marginBottom: 10 };
const button = { marginBottom: 10 };
const heading = { fontWeight: "normal", fontSize: 40 };
const messageBg = { backgroundColor: "white" };
const messageStyle = { padding: "10px", marginTop: 7, borderRadius: 2 };
const messageTitle = { margin: 0, padding: 9, fontSize: 20 };
export default App;
In this beauty above, we're jazzing things up with antd UI components, Amplify's Datastore API, and the Message model. Our app fetches messages, listens to real-time changes, and dances to user inputβcreating messages on the go!
π Conclusion
Well, look at you now! You've just unlocked the prowess of AWS Amplify in building cloud-kissed apps. π©οΈ We played around, got our hands dirty, and brought a real-time message board app to life using AWS Amplify and React. All using the wondrous Datastore API.
By following this cool guide, you're all set to let AWS Amplify back your next big thing. Go make waves! π
See you around in the cloud! Till next time! βοΈ
Top comments (0)