skip to Main Content

I want to make an api call whenever that screen is focused, in mobile application I have an idea that we can use useFocuseffect () but in web how can I implement this please let me know in web how can I make an api call whenever that screen is focused

2

Answers


  1. You can use the useEffect() hook
    Or the useLayoutEffect() hook depending on how fast you want your api calls to be made.

    useEffect() is triggered after DOM Manipulations are painted

    useLayoutEffect() is triggered synchronously before DOM Manipulations are painted

    Login or Signup to reply.
  2. You can listen to the focus event on the window object for this:

    useEffect(() => {
      // The function that will make the wanted API call
      function makeApiCall() {
         // Your code here
      }
      
      // Add an event listener on the window object for the focus event
      // This will call the makeApiCall function whenever the window gets focus
      window.addEventListener('focus', makeApiCall)
    
      // In the cleanup function, we need to remove the event listener added 
      // previously
      return () => { 
        window.removeEventListener('focus', makeApiCall)
      }
    }, [])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search