1import React, { useState, useEffect } from "react";
2import socketIOClient from "socket.io-client";
3const ENDPOINT = "http://127.0.0.1:4001";
4
5function App() {
6 const [response, setResponse] = useState("");
7
8 useEffect(() => {
9 const socket = socketIOClient(ENDPOINT);
10 socket.on("FromAPI", data => {
11 setResponse(data);
12 });
13 }, []);
14
15 return (
16 <p>
17 It's <time dateTime={response}>{response}</time>
18 </p>
19 );
20}
21
22export default App;
1connect to the socket server on component mount with useEffect
2save each new incoming message in the component's state.
3
4function App() {
5 const [response, setResponse] = useState("");
6
7 useEffect(() => {
8 const socket = socketIOClient(ENDPOINT);
9 socket.on("FromAPI", data => {
10 setResponse(data);
11 });
12 }, []);
13
14 return (
15 <p>
16 It's <time dateTime={response}>{response}</time>
17 </p>
18 );
19}