6

I'm creating a chat app with a user and agent. I'm trying to retrieve the messages when the agent replies on his separate Rainbow UI. The problem is that this can only be done via an event listener as shown in the documentation. Can someone help me, where and how can I document.addEventListener in React?

Note: getMessageFromConversation() api doesn't work because by default, once the full messsage history has been seen, calling this api will return an error. I've tried it.

Thanks in advance!

2 Answers 2

9

If you're using class based components then you can use componentDidMount and componentWillUnmount to add and remove the listener respectively, like this:

class Hello extends React.Component {
  doSomething = () => {}

  componentDidMount() {
    window.addEventListener('scroll', this.doSomething)
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.doSomething)
  }
}

If you're using hooks then you can use useEffect to add and remove listener like this:

function Hello() {
  useEffect(() => {
    const doSomething = () => {};

    window.addEventListener("scroll", doSomething);
    return () => {
      window.removeEventListener("scroll", doSomething);
    };
  }, []);
}

Sign up to request clarification or add additional context in comments.

Comments

1

You can add an eventListener in react doing so in the componentDidMount so it will be done when the component is mounted.

componentDidMount() {
    document.addEventListener(...)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.