Home > database >  How can focus events filtered out coming from select item changes?
How can focus events filtered out coming from select item changes?

Time:09-05

focus events are listened, component is notified when browser / page is opened again:

    useEffect(() => {
        //Add a listener on the window object
        window.addEventListener('focus', onFocus)

        //Clean listeners
        return () => {
            window.removeEventListener('focus', onFocus)
        }
    }, [])

    const onFocus = (e) => {
        if (e.) { // <--------------
            return
        }
        dispatch(
            log({
                text: 'onFocus get called',
            })
        )
        callBuyTicket2()
    }

But selecting other option in select item on the page will fire also focus event. Is it a way to filter those events out?

enter image description here

CodePudding user response:

I think you have to use a state and the onblur event.

const [isCurrentlyInPage, setIsCurrentlyInPage] = useState(true)
useEffect(() => {
    //Add a listener on the window object
    window.addEventListener('focus', onFocus)
    window.addEventListener('blur', onBlur)

    //Clean listeners
    return () => {
        window.removeEventListener('focus', onFocus)
        window.removeEventListener('blur', onBlur)
    }
}, [])

const onFocus = (e) => {
    if(!isCurrentlyInPage){
        setIsCurrentlyInPage(true)
        //your code
    }
}

const onBlur = () => {
    setIsCurrentlyInPage(false)
}
  • Related