I would like to terminate a Twilio call. The issue however is that, when I resolve the promise to connect the call and update a state with the call object and try to access this state outside the promise (inside a 'Terminate Call' button), I get undefined, as though the state has not been updated.
My console.log seems to indicate that the state has not been updated as assumed.
Here is my code:
//this is a global variable
let checkCall = false
const [call, setCall] = useState();
...
useEffect(() => {
function selectDriver() {
driverInState.current = sortUsersAlphabetically([user.username, matchedUserState.current])[0]
}
console.log('!!!*** how many times is twilio being called ***!!!')
WebSocketInstance.connect()
selectDriver()
const params = {
roomName: roomName, participantLabel: user.username
};
if(checkCall === false){
if (!call) {
const callPromise = device.connect({ params });
callPromise.then((twilioCall) => {
console.log(' ***what is call', twilioCall)
setCall((prev) => twilioCall);
setCallConnected(true)
});
}
if (!participants.current.includes(user.username)) {
participants.current.push(user.username);
}
checkCall = true
}
}, [roomName, user, call, device, participants, driverInState,matchedUserState,sortUsersAlphabetically]);
const handleLeaveRoom = () => {
console.log("INSIDE FUNCTION TO TERMINATE CALL", JSON.stringify(call));
call.disconnect();
};
const endCall = () => {
handleLeaveRoom();
setState({ ...state, createdRoomTopic: null });
};
...
return (
<>
<button onClick={ ()=> endCall() }>End Call</button>
...
</>
)
Inside the useEffect, I can console log the call object in state. However, in the handleLeaveRoom function, I cannot console log the call object