Ajit Kumar
Ajit Kumar

Reputation: 417

React State returning Undefined

I am having a state called mediaRecorder which is empty initially. After a particular process this state is updated to a new value. But when the value of this state is called in the useEffect it is returning the initial empty value:

  const [mediaRecorder, setMediaRecorder] = useState();

  ...
  const func = () => {
   setMediaRecorder(newVal); //updating the value
  }

  ...
  useEffect(() => {
    socket.on("serveVideo", (_) =>    //this is called after the 'func' function
       mediaRecorder.stop();  // undefined or empty
    );

    return () => {
      socket.off("vidBlob");
    };
  }, [mediaRecorder]);

Upvotes: 2

Views: 81

Answers (1)

krishnaacharyaa
krishnaacharyaa

Reputation: 24950

UseEffect() runs asynchronously

i.e If code order is

someFunction()
...
...
useEffect((){},[mediaRecorder]);

It doesn't mean that useEffect is executed after someFunction. Infact useEffect is executed based on the dependency array which is mediaRecorder in this case.

UseEffect() first runs when mediaRecorder is null i.e initially, it next runs only when the mediaRecorder changes irrespective of where it lies in the code segment.

As the first time mediaRecorder will be null, try to check if it's not null, only then perform operation

useEffect(() => {
 if(mediaRecorder!=null){                  //👈 Try to wrap inside this if statement
   socket.on("serveVideo", (_) =>  mediaRecorder.stop(););
 }
  return () => {
    socket.off("vidBlob");
  };
}, [mediaRecorder]);

Upvotes: 3

Related Questions