forked from aws-samples/websocket-api-cognito-auth-sample
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecho.tsx
More file actions
118 lines (98 loc) · 3.02 KB
/
Copy pathecho.tsx
File metadata and controls
118 lines (98 loc) · 3.02 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import { FC, useEffect, useReducer, useState } from "react";
import { fetchAuthSession } from "aws-amplify/auth";
import { Typography, Button, TextField, Stack } from "@mui/material";
import { SubmitHandler, useForm } from "react-hook-form";
import config from "../config";
type EchoInput = {
message: string;
};
const Echo: FC = () => {
const { register, handleSubmit, reset } = useForm<EchoInput>();
const [status, setStatus] = useState("initializing");
const [messages, setMessages] = useState<string[]>([]);
const [client, setClient] = useState<WebSocket>();
const [closed, forceClose] = useReducer(() => true, false);
const initializeClient = async () => {
const currentSession = await fetchAuthSession();
const idToken = currentSession.tokens?.idToken;
const client = new WebSocket(`${config.apiEndpoint}?idToken=${idToken}`);
client.onopen = () => {
setStatus("connected");
};
client.onerror = (e: any) => {
setStatus("error (reconnecting...)");
console.error(e);
setTimeout(async () => {
await initializeClient();
});
};
client.onclose = () => {
if (!closed) {
setStatus("closed (reconnecting...)");
setTimeout(async () => {
await initializeClient();
});
} else {
setStatus("closed");
}
};
client.onmessage = async (message: any) => {
const messageStr = JSON.parse(message.data);
console.log(messages);
setMessages((prev) => [...prev, messageStr.message]);
};
setClient(client);
};
const sendMessage: SubmitHandler<EchoInput> = async (input) => {
if (client != null) {
client.send(input.message);
reset({ message: "" });
}
};
const handleUserKeyDown = (e: any) => {
if (e.key === "Enter" && !e.shiftKey) {
handleSubmit(sendMessage)(); // this won't be triggered
}
};
useEffect(() => {
initializeClient();
return () => {
if (client != null) {
forceClose();
client.close();
}
};
}, []);
return (
<Stack justifyContent="center" alignItems="center" sx={{ m: 2 }}>
<Typography variant="h4" gutterBottom>
WebSocket echo 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 WebSocket server
</Typography>
{messages.map((msg) => (
<Typography sx={{ color: "#808080" }}> {msg}</Typography>
))}
</Stack>
);
};
export default Echo;