programista4k
programista4k

Reputation: 45

Increment value with eventListener

Given:

export default function ComponentA(props) {

    const [x, setX] = useState(0)
    
    useEffect(() => {
        connect("http://localhost:18200/events/agg/dotusd");
    })

    const connect = (url) => {
        const es = new EventSource(url, { withCredentials: false });
        es.addEventListener('heartBeat', handleHeartBeat);
    };

    const handleHeartBeat = (event) => {
        setX((x) => x + 1)
        const currentdate = new Date(); 
        const datetime = " "
                + currentdate.getHours() + ":"  
                + currentdate.getMinutes() + ":" 
                + currentdate.getSeconds();
        console.log("time =", datetime + "; x =", x)
    }

    return (
        <div>
            <ComponentB key='1' x={x} />
        </div>
    );
}

When: heartbeat event occurs.

Then: increment x value and log it to the console, so:

1  
2  
3  
4  
...  

Result: it makes a strange recursion:

0  
0 1  
0 1 2  
0 1 2 3  
...  

Why and how to fix it?

enter image description here

Upvotes: 0

Views: 73

Answers (1)

larz
larz

Reputation: 5766

Add an empty array as the second argument to useEffect. This tells react to only run that code once, when the component mounts. Currently, every time this component re-renders, its adding another event listener.

useEffect(() => {
    connect("http://localhost:18200/events/agg/dotusd");
}, [])

Upvotes: 1

Related Questions