React useState hook getting oldState inside a callback

My state has such form:

  const [state, setState] = useState({     ua: null,     session: null,     pcConfig: {},     indicatePower: null,     indicateMic: null,     indicateSignIn: null,     indicatePhone: null,     isMuted: false,   }); 

I have such useEffect function.

useEffect(() => { JsSIP.debug.enable("JsSIP:*"); if (dn != null) {   ...   ua.on("newRTCSession", (e) => {     setState((prevState) => ({ ...prevState, session: e.session }));     let waitingIceCandidates = false;      if (e.originator === "remote") {        ...       e.session.on("notify-talk", () => {         //stopSound();         setTimeout(answer, 100);       });        e.session.on("accepted", () => {         playSignal();       });     }    });    setState((prevState) => ({ ...prevState, ua: ua }));    ua.start(); } else {   console.log("ERROR: DN is not passed to softphone!"); } }, []); 

And this callback function

const answer = () => {     console.log("ANSWER", state);     if (       state.ua != null &&       state.session != null &&       state.session.isInProgress()     ) {       navigator.mediaDevices         .getUserMedia({           audio: true,         })         .then((stream) => {           state.session.answer({             mediaConstraints: {               audio: true,               video: false,             },             pcConfig: state.pcConfig,             mediaStream: stream,           });         });     }   }; 

So, the problem is when answer function gets called state condition is still initial though if I create another useEffect function and provide the state inside an array of arguments it updates!! I have no idea what is the problem with this code. Also there was a problem(maybe it helps) with setState function – it works properly only via callback with prevState and doesn`t work like this

setState({...state, indicatorPower: true}) 
Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.