Jantoma21
Jantoma21

Reputation: 485

How to pass eventName to listener function without loosing the ability of closing off socket?

In my React component I need to connect multiple socket and listen them. In my useEffect I have following code and it does what I want but useEffect return function not making sockets off.

socket.off(variables[i], (msg) => formulaParser(msg, variables[i]))

I believe problem is about passing eventName(variable[i]) in listener function because if I wrote something like this, it works:

socket.off(variables[i], formulaParser);

But I need variable[i] in my formulaParser function. How can pass eventName to listener function without loosing the ability of closing off socket?

My useEffect:

  useEffect(() => {
    const variables = ["variable1", "variable2", "variable3"];
    const formulaParser = (value: number, eventName: string) => {
      console.log(value, eventName);
    };
    for (let i = 0; i < variables.length; ++i) {
      socket.on(variables[i], (msg) => formulaParser(msg, variables[i]));
    }
    return () => {
      for (let i = 0; i < variables.length; ++i) {
        socket.off(variables[i], (msg) => formulaParser(msg, variables[i]));
      }
    };
  }, []);

Upvotes: 0

Views: 42

Answers (2)

The useEffect callback runs twice for initial render, probably because the component renders twice. After state change the component renders twice but the effect runs once.

Upvotes: 0

darrachequesne
darrachequesne

Reputation: 816

I think you'll need to keep track of the listener functions:

useEffect(() => {
  const variables = ["variable1", "variable2", "variable3"];
  const formulaParser = (value: number, eventName: string) => {
    console.log(value, eventName);
  };
  const listeners = [];
  for (let i = 0; i < variables.length; ++i) {
    const listener = (msg) => formulaParser(msg, variables[i]);
    socket.on(variables[i], listener);
    listeners.push(listener);
  }
  return () => {
    for (let i = 0; i < variables.length; ++i) {
      socket.off(variables[i], listeners[i]);
    }
  };
}, []);

Upvotes: 1

Related Questions