fix: update useXRSessionModeSupported to events to update #464
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
My problem
I had a React Dom component that I wanted to show buttons to enter VR/AR, or show not supported when not supported. These work great in development when they've been added via HMR, but on fresh reload, when IWER hasn't loaded, they would switch to "XR not supported" because that's what useXRSessionModeSupported told them and stay that way because there wasn't anyway for them to know IWER finishes setting up. I can go with polling solution in this case, but I felt we could make it better with events.
In IWER I added meta-quest/immersive-web-emulation-runtime#119 which will make use of the
devicechangeevent. I'm hoping they will accept this change, but even if not, handling thedevicechangeevent and updating the hooks seems like the right idea.There is an extra twist, IWER replaces the
navigator.xrobject, so we have to unsubscribe from the previous object and subscribe to the new one.Solution
Replaces the implementation that kept state in a useMemo closure with a singleton external store that lives outside React's lifecycle. This ensures useSyncExternalStore works correctly across component mounts. With the addition of event this is a lot more like the
navigator.onlineexample they give in the react docs.Applications need to detect when XR devices become available and update their UI accordingly. The hook now listens to devicechange events and maintains backward compatibility with the optional onError parameter.
I would be happy to add a test if that would be helpful.