Aaronius / penpal

A promise-based library for securely communicating with iframes via postMessage.
MIT License
381 stars 56 forks source link

Examples for using with React Hooks #77

Closed joeblas closed 2 years ago

joeblas commented 2 years ago

It would be nice to have some examples using React, possibly even adding custom hooks for both connectToParent and connectToChild. I've been playing around with penpal in a React project and I can't seem to come up with the best way to destroy the connection. Any feedback would be appreciated:

const useConnectToChild = (iframe, {methods}) => {

  const [connection, setConnection] = useState(null)
  useEffect(() => {
    if (iframe) {
      setConnection(connectToChild(iframe, {methods}))
    }
    return () => connection.destory() // You can't really call connection.destroy here, it will cause an endless re-render. 
    // Maybe throw it in a separate useEffect? 
  }, [connection])

  return [connection]
}
Aaronius commented 2 years ago

Good idea @joeblas!

Looking at your code, I don't think you want connection as a dependency of useEffect. I haven't tested it, but logically I think what's happening with the code you have is that the first time the component renders, useEffect will be called and setConnection(connectToChild(iframe, {methods})) will be called inside useEffect. This will set the connection state to the new connection object Penpal returns. Since the connection state changed, the component will re-render and the useEffect will run again (because the useEffect sees that the connection dependency has changed). This will call setConnection(connectToChild(iframe, {methods})) again, which will set the connection state to a new connection object, which will re-render the component, which will re-run the useEffect....and it re-renders endlessly.

I think you probably want to remove connection as a useEffect dependency and maybe add iframe and methods as dependencies, depending on what you want to happen when either of those change.

Aaronius commented 2 years ago

Feel free to give https://www.npmjs.com/package/react-penpal a shot as well. If you try it out, let me know how it goes for you.

joeblas commented 2 years ago

Hey @Aaronius, thanks for the reply! After looking at react-penpal, I had some "ah-ha" moments. Perhaps it'd be a good idea to add a link to react-penpal in the readme. What do you think? I can add in the link right after the Typescript section or at the very bottom.

Aaronius commented 2 years ago

Glad you found what you needed! I've added the link to the readme. Thanks for the feedback.