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
I got the functionality I was looking for using the useRef function as follows:
Though this works, it doesn't answer why counterHook doesn't get updated though. If anyone can answer that, that would be helpful!
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:
option 2, use useEffect