DEV Community

Cover image for Boost Your React Apps in 2023: Real-time Integration with AWS Amplify & Datastore Guide πŸš€
Rahul Ladumor
Rahul Ladumor

Posted on • Edited on

Boost Your React Apps in 2023: Real-time Integration with AWS Amplify & Datastore Guide πŸš€

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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Now, let's churn out the models for our app:

npm run amplify-modelgen
Enter fullscreen mode Exit fullscreen mode

Boom! Models ready. πŸŽ‰ To initialize our Amplify project in the wild, vast cloud:

amplify init
Enter fullscreen mode Exit fullscreen mode

A bit more setup (like naming our environment), then we'll deploy with:

amplify push
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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! 🌊

Who said it's not fun to code?

See you around in the cloud! Till next time! ✌️


Top comments (0)