1110
1110

Reputation: 6829

How can I pass parameter to event listener in react

I have component like this:

import React, { useEffect } from 'react';

const WindowFocusHandler = ({store}) => {
  // here store object is valid and work
  useEffect(() => {
    window.addEventListener('focus', () => {
      console.log('Tab is in focus... but no store object here', store);
    
    });
  });

  return <></>;
};

export default WindowFocusHandler;

And I am trying to pass store object inside listener function but failed what ever I try.

Upvotes: 2

Views: 1103

Answers (1)

Ross Sheppard
Ross Sheppard

Reputation: 870

Try this:

import React, { useEffect } from 'react';

const WindowFocusHandler = ({ store }) => {
  useEffect(() => {
    const fn = () => {
      console.log('Tab is in focus...', store);
    };

    window.addEventListener('focus', fn);
    return () => window.removeEventListener('focus', fn);
  }, [store]);

  return <></>;
};

export default WindowFocusHandler;

Upvotes: 3

Related Questions