I have a react component that has an useEffect like this:
// MQTT client
const client = mqtt.connect(brokerUrl, {
clientId,
clean: true,
username: import.meta.env.VITE_MQTT_BROKER_USERNAME,
password: import.meta.env.VITE_MQTT_BROKER_PASSWORD,
});
useEffect(() => {
// Set up event handlers
if (client) {
client.on("connect", () => {
client.subscribe("rfid", () => {});
});
client.on("message", (topic, message) => {
if (topic === "rfid") {
handleRfidCard(message.toString());
// console.log({ message });
}
});
}
}, [client, handleRfidCard]);
Inside the handleRFID, I call 2 apis using useMutation:
const rfidCard = useGetRfidCardByPhysicalCard();
const handleRfidCard = (rfidID: string) => {
if (rfidID) {
rfidCard.mutate(rfidID, {
onSuccess: (data) => {
capture(data.id, data.type);
},
});
rfidHistory.mutate(rfidID);
}
};
Here’s an example of my mutation hook:
import { instanceCoreApi } from "@/provider/setupAxios";
import { useMutation } from "@tanstack/react-query";
import { RFIDCard_API } from "../apis";
export const useGetRfidCardByPhysicalCard = () => {
return useMutation({
mutationFn: async (cardID: string) => {
const res = await instanceCoreApi.get(RFIDCard_API.GET_BY_CARD_ID, {
params: {
cardID,
},
});
return res.data;
},
});
};
I expect that each time receive the message from MQTT broker, the 2 apis will be called. Currently, they’re being called incrementally, which mean:
#1 message: 2 calls
#2 message: 4 calls
#3 message: 6 calls
This is really confusing as it slows down the web as it gets more messages. Can anyone help me?