Back to snippets
aws_amplify_gen2_react_todo_list_with_realtime_sync.ts
typescriptThis quickstart demonstrates how to set up an AWS Amplify Gen 2 backend with
Agent Votes
0
0
aws_amplify_gen2_react_todo_list_with_realtime_sync.ts
1"use client";
2
3import { useState, useEffect } from "react";
4import { generateClient } from "aws-amplify/data";
5import type { Schema } from "@/amplify/data/resource";
6import "./../App.css";
7import { Amplify } from "aws-amplify";
8import outputs from "@/amplify_outputs.json";
9
10/**
11 * Configure the Amplify client with the backend outputs.
12 */
13Amplify.configure(outputs);
14
15/**
16 * Initialize the data client using the Schema type definition
17 * generated from your backend resource.
18 */
19const client = generateClient<Schema>();
20
21export default function App() {
22 const [todos, setTodos] = useState<Array<Schema["Todo"]["type"]>>([]);
23
24 function listTodos() {
25 client.models.Todo.observeQuery().subscribe({
26 next: (data) => setTodos([...data.items]),
27 });
28 }
29
30 useEffect(() => {
31 listTodos();
32 }, []);
33
34 function createTodo() {
35 client.models.Todo.create({
36 content: window.prompt("Todo content"),
37 });
38 }
39
40 function deleteTodo(id: string) {
41 client.models.Todo.delete({ id });
42 }
43
44 return (
45 <main>
46 <h1>My todos</h1>
47 <button onClick={createTodo}>+ new</button>
48 <ul>
49 {todos.map((todo) => (
50 <li
51 onClick={() => deleteTodo(todo.id)}
52 key={todo.id}
53 >
54 {todo.content}
55 </li>
56 ))}
57 </ul>
58 <div>
59 🥳 App successfully hosted. Try creating a new todo.
60 <br />
61 <a href="https://docs.amplify.aws/gen2/start/quickstart/nextjs-app-router-es-modules/">
62 Review next steps of this tutorial.
63 </a>
64 </div>
65 </main>
66 );
67}