1

I am trying the convert class based component to the functional component.

I'm basically trying to connect to a socket and I couldn't come up with a solution on how to separate this function.

  constructor(props) {
    super(props);
    this.state = {
      message: "",
    };

    this.waitForSocketConnection(() => {
      WebSocketInstance.addCallbacks(
        this.setMessages.bind(this),
        this.addMessage.bind(this)
      );
      WebSocketInstance.fetchMessages();
    });
  }
  waitForSocketConnection(callback) {
    const component = this;
    setTimeout(function () {
      if (WebSocketInstance.state() === 1) {
        console.log("Connection is made");
        callback();
        return;
      } else {
        component.waitForSocketConnection(callback);
      }
    }, 100);
  }

I used the function in useEffect (corresponding to componentDidMount), but I couldn't get the data from the socket. When I called the method directly in the functional component instead of useEffect, I saw messages coming, but for some reason, I don't know why, when the waitForSocketConnection method is called, it affects the ui and makes it unusable. I can't click anywhere in the ui.

  useEffect(() => {
    waitForSocketConnection(() => {
      WebSocketInstance.addCallbacks(setMessages, addMessage);
      WebSocketInstance.fetchMessages();
    });
  }, []);

  function waitForSocketConnection(callback) {
    const component = this;
    setTimeout(function () {
      if (WebSocketInstance.state() === 1) {
        console.log("Connection is made");
        callback();
        return;
      } else {
        component.waitForSocketConnection(callback);
      }
    }, 100);
  }

1 Answer 1

0

I have solved my problem by removing 'this' from the waitForSocketConnection function. See below

  function waitForSocketConnection(callback) {
setTimeout(function () {
  if (WebSocketInstance.state() === 1) {
    console.log("Connection is made");
    callback();
    return;
  } else {
    waitForSocketConnection(callback);
  }
}, 100);}
Sign up to request clarification or add additional context in comments.

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.