krakenjs / post-robot

Cross domain post-messaging on the client side using a simple listener/client pattern.
Apache License 2.0
741 stars 92 forks source link

post-robot in React - cannot read properties of undefined (send) #115

Open lcpages opened 1 year ago

lcpages commented 1 year ago

I have install the post-robot package to my react project.

My project works as a web app which is embedded into a Web Client application and displayed within an IFrame. I know this web client uses post-robot library to handle communication events and I also know it is has an EventListening set on "loading".

Like any other packages, I have imported post robot in my main app component

import { postRobot } from 'post-robot'

I tried to send the corresponding message the webclient is expecting :

const sendMessage = (message, success) => {
    //parent window is the holding web client, message is "loading", success is false
    postRobot.send(window.parent, message, success)

however, when this function is called in the hook at runtime, an error occurs saying that React does not recognize '.send()' as a valid method.

error1

I am puzzled. React seems to not recognize post-robot package, however, VS does not preventively throw any warning/errors (like it usually does) which would mean the package has been installed successfully. Am I doing this wrong or is post-robot not meant to be used on a React project ?

zackspear commented 1 year ago

You need to use the default export

import postRobot from 'post-robot'; // will work

Not a named export

import { postRobot } from 'post-robot'; // won't work

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

lcpages commented 1 year ago

@zackspear , thank you for the answer. It works.