🔮 Sanity Create is here. Writing is reinvented. Try now, no developer setup

Error handling for network unavailability in useListeningQuery hook.

7 replies
Last updated: May 5, 2023
Hi Sanity Folk,I’m using
user T
’s (very convenient!) useListeningQuery() hook to build a custom input component. I use it to grab some data from the Content Lake when the component loads, and to update values when they change (either from the current author’s, or someone else’s input). It’s all working fine … except when I try to catch errors due to network unavailability. If I return a component (as User models in the repo), I get an
Error: Could not establish EventSource connection
and an additional
TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable
message in the console. The component also runs continuously.Here’s the relevant code (I’m in Studio version 3.8.3):


	// Get the videoId and playerType from the document & listen for changes
	const { data, loading, error }: { data: any; loading: boolean; error: any } = useListeningQuery<SanityDocument[]>(
		`*[_id == $documentId]`,
		{
			params: { documentId },
			initialValue: [],
		},
	);
	if (loading) return <Spinner />;

	// ⬇ TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.
	// ⬇ Error: Could not establish EventSource connection
	if (error) {
		console.log('error: ', error);
		return <Card tone="critical">There has been a problem</Card>;
	}
Any ideas for how to handle that potential error state more gracefully?
Thanks!
May 3, 2023, 6:51 PM
I can probably give you a better example for handling the error. How are you simulating network availability?
May 3, 2023, 8:19 PM
Great! I’m just toggling to “Offline” in the “Throttling” menu in the Network tab of Chrome Dev Tools once the page is loaded.
May 3, 2023, 8:21 PM
I’ll take a look tomorrow! 🤞
May 3, 2023, 8:24 PM
Fantastic. Thank you!
May 3, 2023, 8:24 PM
Hey User,
I’m pushing a new version of the package now which has better error handling, it will stop retrying the query in the event of an error. This means however you’d need to build your own mechanism to
reload the component in case of an error.
The error message you’re mentioning comes from the documentStore itself – which this hook is just a convenient wrapper around. So there’s nothing more this hook could do to prevent or handle it.
May 4, 2023, 8:54 AM
Great! Thanks User. I’ll try that out.
May 4, 2023, 4:10 PM
That did what I needed — thanks User!
May 5, 2023, 10:03 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?