Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ReactJs code Reading/Connecting two times to my APi

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading