LF Video where Theo talks about using react query for ping
I can't remember what the video is. But I remember he saying that for ping they are using react query a bunch for handling microphone and other devices instead of global state management. I'm building something that also has to deal with microphone and video devices and I wanted to rewatch that video because I can't really see how react query can be helpful
4 Replies
React Query handles async functions and keeps track of all the internal state of them (error, loading, data, etc)
Connecting to external devices isn’t a synchronous task, JavaScript can’t know when the connection is going to be established, so React Query definitely helps with that and with managing all the lifecycle of the async operation
But to establish a connection with, for example, a microphone you need permission. So it may look like you can handle this with react query:
navigator.mediaDevices.getUserMedia({ audio: true })
And you return from the react query the stream, and if it has loaded, etc. However, react query will retry things when they error which can cause issue so you would have to disable that. Then you have the media stream that comes out of react query and within react you have to pass that to whatever media stream handler you have. which is weird because I don't really want to deal with any of this within react, I want it as outside of react as possible. Idk it doesn't feel like it makes sense, maybe I'm just over thinking it
theoretically, you could wrap all the logic to get the stream and the controller itself in the query function for react query and just consume it in the component itself
react query afaik only requires a function that returns a promise that resolves to some data or throws an error
Yes that’s true, as long as you pass an async function you’re good, whatever that async function does won’t matter to React Query.
Just by doing that now you have control over the lifecycle of the async function by appending methods (onMutate, onSuccess, onError, onSettled) and the state by just calling the hook in your component
With that, you could show some UI while the devices are connecting, then show a toast if the connection completed correctly or failed.