I am trying to implement a video call room where users can share their audio and video using Agora and React. In fact, I have a working example but only with native javascript without React.
what I try to do is each time the handleUserPublished is running to store the remote user who published.
The problem with that is when the user publishes, and if he is sharing both video and audio tracks then the event is triggered twice since each track i.e. audio and video causes handleUserPublished to run. this is my code for the Room component:
let handleUserPublished = async (user, mediaType) => {
let dataElement = // create dataElement based on user
if (mediaType === "video") {
setNewRemoteVideo(user);
setPlayers((prev) => [...prev, dataElement]); // I am not sure put this here or in the other case but I have to update 'players' state only one time
}
if (mediaType === "audio") {
setNewRemoteAudio(user);
// or put setPlayers((prev) => [...prev, dataElement]) here
}
};
useEffect(() => {
const joinRoomInit = async () => {
// create Agora connection
client.on("user-published", handleUserPublished);
};
joinRoomInit();
}, []);
As you can see in the above code I create two different states, newRemoteAudio and newRemoteVideo this is because depending on mediaType I chose what state to update with the received user.
Note that user when mediaType === "video" is different from user when mediaType === "audio" however the user object coming with the second handleUserPublished event is enough to store because it contains both data but I can never guess which one is going to be the second one the order is not always the same that's why I store both users in different state so after that, I can merge them. This somehow helps but I would like to store the remote user once and for all (the second run), the same for players.
My goal is to add dataElement to players state once the remote user is added to the other state because in JSX I am returning players but I am struggling to do that since the event handleUserPublished runs twice and I don't know which order gonna happen so I don't know when exactly to update players state, I want to do it the second time handleUserPublished runs so I don't have to set audio data and video data separately but only once (the second run) and the same of players state.
I need your help, thank you