I wrote a custom hook, it maintains a state and exports that variable and it is used in a component. Inside the hook, the variable is never updated, but inside the component it is. Here is some short hand code to demonstrate it.
// useCustomHook.js
export default useCustomHook => {
const [ quesiton, setQuestion ] = useState("")
useEffect(() => {
emitter = new NativeEventEmitter(nativeModule)
emitter.addListener('eventUpdate', e => {
setQuestion(e) // e == "testing"
console.log(question) // question == ""
})
emitter.addListener('eventEnd', e => {
setQuestion(e) // e == "testing"
finishEvent()
})
const finishEvent = () => {
console.log(question) // question == ""
}
}, [])
return [ question ]
}
// component.js
export default component = props => {
const [ question ] = useCustomHook()
return (
<Text>{question}</Text> // question == "testing"
)
}
Every time the update event happens, question is updated in the component. But in that same function, question is always an empty string. I can't make sense of what is happening here, it must be some weird behavior of the useState setter that I don't understand.
To add some clarification, as for the console.log
in the update event, I am not expecting it to output the correct value in that call. It is subsequent calls where the value is never updated. The update function will get called 20-30 times as new values are sent to it before the end event is triggered. This can happen over the span of 20-30 seconds. The value that is consoled out is always an empty string.