Home > other >  React State returning Undefined
React State returning Undefined

Time:01-02

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]);

CodePudding user response:

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){                  //           
  • Related