Duplication of data through event source when react app opened in two tabs

Viewed 13

I have an app that uses event source to get the data from a spring boot backend. The issue I am facing is that when I open the same page in the new tab, the already loaded tab fetches the data again and duplicates the data in the table. I am not sure why that happens, with every tab do we not get an instance of the app and therefore each tab should be its on instance and should initiate a new event source connnection with the back end? The code is shown below:

export default function CurrentShifts() {
  const [shiftArray, setShiftArray] = useState<any>([]);
  
  useEffect(() => {
    setTableTypeFunc();
    const eventSource = new EventSource(baseUrl + "/shifts/getAllShifts", {
      withCredentials: true,
    });
    eventSource.onopen = (event: any) => console.log("open", event);

    eventSource.onmessage = (event: any) => {
    
      setShiftArray((oldArray: any) => {
        return [...oldArray, JSON.parse(event.data)];
       });
    };
    eventSource.onerror = (event: any) => {
      console.log(event);
      eventSource.close();
    };
    return () => {
      eventSource.close();
     
    };
  }, []);

 
  return (
    
            <div className="table">
              <BasicTableButtons dataArray={shiftArray} />
            </div>
)
         
       

The table in the new tab is shown below: enter image description here

The table in the original tab is shown below: enter image description here

0 Answers
Related