skip to Main Content

I have the following react rendering

<p>Send Counter: {counterHook}</p>
<button onClick={() => startRecording()}>Start</button>

once startRecording gets called, the callback function onTranscribe is called:


const [counterHook, updateCounter] = useState(0)

const onTranscribe = async (blob: Blob) => {

        console.log("onTranscribe")

        updateCounter(counterHook => counterHook + 1)
        console.log(counterHook)
}

I am confused because the value in the

tag updates and I can see it but the console log of counterHook stays at 0. Why is that? Even if it’s because of the asynchronous nature, on the next call of onTranscribe, the value should update, but it always stays at 0.

I’ve tried changing to use a let variable but that variable seems to get reset every time the DOM gets re-rendered by other functions that interact with the states.

2

Answers


  1. Chosen as BEST ANSWER

    I got the functionality I was looking for using the useRef function as follows:

    const [counterHook, updateCounter] = useState(0)
    const stateRef = useRef<number>(0);
    
    stateRef.current = counterHook;
    
    const onTranscribe = async (blob: Blob) => {
    
            console.log("onTranscribe")
    
            updateCounter(counterHook => counterHook + 1)
            console.log(counterHook)
            console.log(`stateRef is ${stateRef.current}`)
    }
    

    Though this works, it doesn't answer why counterHook doesn't get updated though. If anyone can answer that, that would be helpful!


  2. React’s setState does not make changes directly to the state
    object.

    to fix your issue
    option 1 save your new count value in seperate object and then call updateCounter:

    const onTranscribe = async () => { 
        console.log("onTranscribe")
        const counter = counterHook +1;
        updateCounter(counter)
        console.log(counter )
    }
    

    option 2, use useEffect

    const onTranscribe = async () => { 
        console.log("onTranscribe")
        updateCounter(counterHook => counterHook + 1)
    }
    
    useEffect(() => {
        console.log(counterHook );
    }, [counterHook ]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search