Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
41 replies
WOLFLEADER

UseEffect not being called

Hey,

I've got a weird bug in my react component
const MqttProvider = ({ children, options }: Props) => {
  const [mqtt, setMqtt] = useState<MqttClient>();
  const [connected, setConnected] = useState(false);

  const onConnect = () => {
    setConnected(true);
  };

  const onClose = () => {
    setConnected(false);
  };

  const initMqtt = async () => {
    try {
      const broker = await getBroker();

      const newMqtt = connect(broker, options);
      newMqtt.setMaxListeners(0);
      newMqtt.on("connect", onConnect);
      newMqtt.on("close", onClose);
      newMqtt.on("error", onClose);
      setMqtt(newMqtt);
    } catch (e) {
      console.error(e);
    }
  };

  useEffect(() => {
    initMqtt();
  }, []);

  useEffect(() => {
    console.log(mqtt?.connected);
  }, [mqtt?.connected]);

  return (
    <MqttContext.Provider value={{ mqtt }}>{children}</MqttContext.Provider>
  );
};

For some reason, when mqtt.connected is changed the useEffect is not called.
For example if i start the broker, it console logs false and then when i disconnect it console logs true
its almost as if the useEffect is reading the previous state.

However if i change the depedency to be my connected state variable instead, it updates perfectly....
( was previously wrapping the return in react.memo but i have removed it for this example, as it presents the same issue, the depedency of mqtt?.connected doesnt get called)
Was this page helpful?