Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger Callback for Async await function which is called on focus event

I'm trying to call a function 'handleCb' on focus of page. This handleCb is an async function and on return of it I want to call another function 'showResult'. The issue is that the cb function showResult is not getting triggered after first time and understandably because it's not part of the focus event. How to get around this issue ? This is inside a React component.

useEffect(() => {
  window.addEventListener('focus', handleCb)
  // I need a way to trigger below after later 'focus' events.
  handleCb().then((result) => showResult(result)) 
}, [])

const handleCb = async () => {
  return await Promise.resolve('good job')
}

A bit more background: showResult cannot be called inside handleCb.

like image 547
Etherealm Avatar asked Jan 26 '26 03:01

Etherealm


1 Answers

You can achieve that by calling both the functions inside focus eventListener

useEffect(() => {
  window.addEventListener('focus', () => {
    return handleCb().then((result) => showResult(result)) 
  })
}, [])
like image 94
Dharmik Patel Avatar answered Jan 28 '26 15:01

Dharmik Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!