using Quick blox for react native receive message handle called multiple time

144 Views Asked by At
    const [chatData, setChatData] = useState([]);
     const emitter = new NativeEventEmitter(QB.chat);
    const receivedNewMessage = (event) => {
        const { type, payload } = event;
        // handle new message
        // type - event name (string)
        var newArray = [...chatData, { "key": payload.id, "body": payload.body, "senderId": payload.senderId, "dateSent": payload.dateSent, }
        ]
        setChatData(newArray);
    }
    const newEmitter = emitter.addListener(
        QB.chat.EVENT_TYPE.RECEIVED_NEW_MESSAGE,
        receivedNewMessage
    )

if i receive one message my payload print for many times , what is the solutions please help.Why it should call many times for one message receive . here i should push user's message in the state hook array and then show it using flat list.

1

There are 1 best solutions below

1
Dorian349 On

Your event is rendered each time you're updating your component, try to move the event to a parent component or use hooks to load it once:

const [loaded, setLoaded] = useState(false);

useEffect(() => {
    const emitter = new NativeEventEmitter(QB.chat);
    const newEmitter = emitter.addListener(
        QB.chat.EVENT_TYPE.RECEIVED_NEW_MESSAGE,
        receivedNewMessage
    )
}, [loaded]) //The useEffect will run once the useState hook has assigned the value to the "loaded" variable.

if(!loaded){
  setLoaded(true);
}