I am new to ReactJs and while I am trying to connect to my API (which is SSE and I would like to stay connected in order to retrieve when new even comes from the server) it prints/consumes the same message 2 times on first page load and later when new event happens it even consumes it couple times, I am not sure if it opens the connection multiple times or I am doing something wrong? Code looks like below
export default function News() {
const [newsList, setNews] = useState([]);
useEffect(() => {
const source = new EventSource("http://localhost:8080/api/v1/news")
source.addEventListener('open', () => {
console.log('SSE opened!');
});
source.addEventListener('message', (event) => {
var message = JSON.parse(event.data)
console.log(message);
setNews(newsList => [...newsList, message]);
});
source.addEventListener('error', (e) => {
console.error('Error: ', e);
});
}, []);
return (
<Table striped bordered hover variant="dark" size="sm">
<thead>
<tr>
<th>Published at</th>
<th>Title</th>
</tr>
</thead>
<tbody>
{newsList.map(({ id, title, published_utc, i }) => (
<tr key={id}>
<td>{published_utc}</td>
<td>{title}</td>
</tr>
))}
</tbody>
</Table>
);
}
And above code prints duplicates in console. I was calling endpoint from browser or postman and I see that backed returns unique data without any issue, something wrong with my UI impl
>Solution :
It’s likely due to the double invocation behavior that Strict Mode introduces. React Strict Mode intentionally double-invokes certain functions, including useEffect, to help detect potential side-effects and other issues in your application.
You can just comment out <React.StrictMode> in index.js of your src dir, as shown below
// <React.StrictMode>
<BrowserRouter>
<Provider store={store}>
<PersistGate persistor={persistor}>
<App />
</PersistGate>
</Provider>
</BrowserRouter>
// </React.StrictMode>