feat: add basic UI2CB and CB2UI communication
By pressing the button, the text in the input field is sent to the CB. Every second, UI receives the current time from CB. ref: N25B-107 ref: N25B-110
This commit is contained in:
68
src/App.tsx
68
src/App.tsx
@@ -1,35 +1,55 @@
|
||||
import { useState } from 'react'
|
||||
import reactLogo from './assets/react.svg'
|
||||
import viteLogo from '/vite.svg'
|
||||
import { useState, useEffect } from 'react'
|
||||
import './App.css'
|
||||
|
||||
function App() {
|
||||
const [count, setCount] = useState(0)
|
||||
const [message, setMessage] = useState('');
|
||||
const [sseMessage, setSseMessage] = useState('');
|
||||
|
||||
const sendMessage = async () => {
|
||||
try {
|
||||
const response = await fetch("http://localhost:8000/message", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ message }),
|
||||
});
|
||||
const data = await response.json();
|
||||
console.log(data);
|
||||
} catch (error) {
|
||||
console.error("Error sending message: ", error);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const eventSource = new EventSource("http://localhost:8000/sse");
|
||||
|
||||
eventSource.onmessage = (event) => {
|
||||
setSseMessage(event.data);
|
||||
};
|
||||
|
||||
return () => {
|
||||
eventSource.close();
|
||||
};
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="App">
|
||||
<div>
|
||||
<a href="https://vite.dev" target="_blank">
|
||||
<img src={viteLogo} className="logo" alt="Vite logo" />
|
||||
</a>
|
||||
<a href="https://react.dev" target="_blank">
|
||||
<img src={reactLogo} className="logo react" alt="React logo" />
|
||||
</a>
|
||||
<input
|
||||
type="text"
|
||||
value={message}
|
||||
onChange={(e) => setMessage(e.target.value)}
|
||||
placeholder="Enter a message"
|
||||
/>
|
||||
<button onClick={sendMessage}>Send Message to Backend</button>
|
||||
</div>
|
||||
<h1>Vite + React</h1>
|
||||
<div className="card">
|
||||
<button onClick={() => setCount((count) => count + 1)}>
|
||||
count is {count}
|
||||
</button>
|
||||
<p>
|
||||
Edit <code>src/App.tsx</code> and save to test HMR
|
||||
</p>
|
||||
<div>
|
||||
<h2>Message from Server (SSE):</h2>
|
||||
<p>{sseMessage}</p>
|
||||
</div>
|
||||
<p className="read-the-docs">
|
||||
Click on the Vite and React logos to learn more
|
||||
</p>
|
||||
</>
|
||||
)
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App
|
||||
|
||||
Reference in New Issue
Block a user