This repository was archived by the owner on Dec 12, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathecho-events.tsx
More file actions
94 lines (82 loc) · 2.57 KB
/
Copy pathecho-events.tsx
File metadata and controls
94 lines (82 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { FC, useEffect, useState } from "react";
import { Typography, Button, TextField, Stack } from "@mui/material";
import { SubmitHandler, useForm } from "react-hook-form";
import { events } from "aws-amplify/data";
type EchoInput = {
message: string;
};
const EchoEvents: FC = () => {
const { register, handleSubmit, reset } = useForm<EchoInput>();
const [status, setStatus] = useState("initializing");
const [messages, setMessages] = useState<string[]>([]);
const initializeClient = async () => {
console.log(`initializing connection...`);
const channel = await events.connect("/default/test");
channel.subscribe({
next: (data) => {
console.log(data);
setMessages((prev) => [...prev, data.message.message]);
},
error: (err) => {
console.error(`error on subscription ${err}`);
setStatus("error");
},
});
setStatus("connected");
console.log("successfully initialized connection.");
return channel;
};
const sendMessage: SubmitHandler<EchoInput> = async (input) => {
await events.post(`/default/test`, { message: input });
};
const handleUserKeyDown = (e: any) => {
if (e.key === "Enter" && !e.shiftKey) {
handleSubmit(sendMessage)(); // this won't be triggered
}
};
useEffect(() => {
const pr = initializeClient();
return () => {
pr.then((channel) => {
channel.close();
// events.closeAll();
console.log(`successfully closed connection.`);
});
setStatus("closed");
};
}, []);
return (
<Stack justifyContent="center" alignItems="center" sx={{ m: 2 }}>
<Typography variant="h4" gutterBottom>
AppSync Events Pub/Sub demo
</Typography>
<Typography variant="subtitle1" sx={{ color: "#808080" }} gutterBottom>
status: {status}
</Typography>
<Stack direction="row" spacing={2} sx={{ m: 5 }}>
<TextField
id="message"
label="Message"
size="small"
required
{...register("message")}
autoComplete="off"
onKeyDown={handleUserKeyDown}
sx={{ width: 400 }}
/>
<Button variant="contained" color="primary" onClick={handleSubmit(sendMessage)}>
Send
</Button>
</Stack>
<Typography variant="subtitle1" gutterBottom>
Messages returned from AppSync Events
</Typography>
{messages.map((msg, i) => (
<Typography sx={{ color: "#808080" }} key={i}>
{msg}
</Typography>
))}
</Stack>
);
};
export default EchoEvents;