Open nionata opened 2 years ago
@raymondhechen any thoughts?
In your useEffect
function, are you sure messages
is defined properly within the nested arrow function? You can test this by just console logging messages
. If your new message is being retained but the old messages are not, then it's likely messages
is undefined or empty in the setMessages
call. This happens because the lines are executed within a separate scope.
useEffect(() => {
const bluetoothManager = new BluetoothManager(
BluetoothMode.Advertise,
() => messages,
(message: Message) => {
console.log(messages, message)
setMessages([...messages, message])
}
)
bluetoothManager.start()
return () => {
// Cleanup logic
}
})
In your
useEffect
function, are you suremessages
is defined properly within the nested arrow function? You can test this by just console loggingmessages
. If your new message is being retained but the old messages are not, then it's likelymessages
is undefined or empty in thesetMessages
call. This happens because the lines are executed within a separate scope.useEffect(() => { const bluetoothManager = new BluetoothManager( BluetoothMode.Advertise, () => messages, (message: Message) => { console.log(messages, message) setMessages([...messages, message]) } ) bluetoothManager.start() return () => { // Cleanup logic } })
Potentially related: https://stackoverflow.com/questions/56511176/state-being-reset
Our root component was originally a functional component with hooks. I noticed this odd behavior though. Every time
setMessages
was called the new message would be retained, but the previous array would be cleared. Additionally, the bluetooth manager would be reinitialized. Since it is inside ofuseEffect
that could only mean that the component is being mounted or updated each time the state is changing. Super odd behavior and not desirable at all.I tried to read up on functional components, but I wasn't enlightened much. I rewrote the component in the OG class syntax and it now it is working as desired. I'm going to leave the class version for now, but I would love to know what's going on here.