Issue
So I've tried multiple solutions to store states but for some reason I can't figure out why I'm loosing the (latest) state of some context. I'm using the following function to get an update on a specific characteristic (I also tried the .monitor() directly on the characteristic).
// This is in the BluetoothProvider
device.monitorCharacteristicForService(
service.uuid,
characteristic.uuid,
onUpdate)
Further I have a function to check the state:
// This is in the BluetoothProvider
const updating = () => {
if (currentMatch != null && currentPerson != null) {
console.log('found person')
} else {
console.log('no person')
}
}
The properties are stored in a reducer with an API/Data MatchProvider
provider:
const { currentMatch, currentPerson } = useContext(MatchDataContext)
The onUpdate
function:
const onUpdate = (
error: BleError | null,
characteristic: Characteristic | null
) => {
updating()
}
The provider is in the the correct place:
<MatchProvider>
<BluetoothProvider>
<Routes>
</Routes>
</BluetoothProvider>
</MatchProvider>
I've tried moving it to another component/provider/redux it doesn't matter. The onUpdate function just can't get the correct state. The UI works perfectly and the state is stored but the onUpdate
method never gets the value.
Solution
Eventually I found the fix, what I did was add the following to the BluetoothProvider
const matchRef = useRef(currentMatch);
const personRef = useRef(currentPerson);
React.useEffect(() => {
matchRef.current = currentMatch
personRef.current = currentPerson
}, [currentMatch, currentPerson]);
This allowed me to listen to the updates from the MatchDataContext
and store the references. Because down the file I had a subscription that was triggered when the bluetooth device received a new message, and this wasn't up-to-date on the latest state.
const onUpdate = (
error: BleError | null,
characteristic: Characteristic | null
) => {
if (matchRef.current != null && personRef.current != null) {
console.log('using match', JSON.stringify(matchRef.current, null, 2))
}
}
For some reason all debugging tools indicated that the value was there, in the BluetoothProvider
but when I called the property it was null.
Answered By - Leon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.