0

I have a HOC "withFirebase" which basically provides my components an interface to communicate with Firebase Services.

Now, I am implementing another HOC "withNotificationsListener" which will receive a component and a path, and then return another component which uses the "withFirebase" HOC.

This is my first time creating a HOC which returns a component that also uses another HOC... My question is basically if this is possible with this code:

const withNotificationsListener = (WrappedComponent, notificationsDBPath) =>
  withFirebase((props) => {
    const listenNotifications = () => {};

    useEffect(() => {
      // TODO - Attach db listener subscription
      return () => {
        // TODO - Detach db listener subscription
      };
    }, []);

    return <WrappedComponent {...props} />;
  });

Following the HOC definition "function that receives a component and returns another component" this make sense to me, because, ultimately, withFirebase returns a component... but I am doubtful since lexically, strictly speaking, I do not return a component directly, but a function.

Would this way of creating this HOC be valid? Or some other way?

Victor Molina
  • 2,353
  • 2
  • 19
  • 49

1 Answers1

0

Seems almost correct since your props can't be Uppercase you would need to destructure them first. When you pass the Component via prop e.g. component={WrappedComponent}

Than in your WithNotificationListener component you can destructure it. e.g. const withNotificationsListener = ({component: WrappedComponent, notificationsDBPath}) => ...

That should work. The link attached goes a little more into depth why you need to destructure the prop. Destructure example

Noah Kanyo
  • 500
  • 1
  • 3
  • 8
  • I am doubtful about this since according to the documentation a HOC is a function (I think not a functional component). If this were the case, a map would have to be passed to the function as an argument to make the destrcutuing, and not as "props" for a classic Component – Victor Molina Nov 28 '20 at 05:36
  • I mean, when using the HOC, I do: const NotificationListenerStackButton = withNotificationsListener( StackButton, notificationsDBPath ); Where StackButton is the original component which will receive the notifications prop from the HOC – Victor Molina Nov 28 '20 at 05:39
  • I see, in this case you may not be able to run useEffect inside the HOC if you are strictly using it as a function. UseEffect can only be rendered inside a react component. – Noah Kanyo Nov 28 '20 at 07:21
  • useEffect is executed because it is not inside the function, it is inside a functional component with ES6 syntax. – Victor Molina Nov 28 '20 at 07:29
  • anyways I have tried to implement the code and works! Thanks! – Victor Molina Nov 28 '20 at 07:30