Skip to content

Instantly share code, notes, and snippets.

@SimeonGriggs
Last active November 30, 2022 05:59
Show Gist options
  • Select an option

  • Save SimeonGriggs/ee7a3fb212625bf39d210f311642eb7e to your computer and use it in GitHub Desktop.

Select an option

Save SimeonGriggs/ee7a3fb212625bf39d210f311642eb7e to your computer and use it in GitHub Desktop.
A custom hook for making and listening to document changes
import React, {useEffect, useState, useRef} from 'react'
import documentStore from 'part:@sanity/base/datastore/document'
import {catchError} from 'rxjs/operators'
type ReturnShape = {
loading: boolean
error: boolean
data: any
}
export default function useListeningQuery(query: string, queryParams: any) {
const [loading, setLoading] = useState(true)
const [error, setError] = useState(false)
const [data, setData] = useState(null)
const subscription = useRef(null)
useEffect(() => {
if (query) {
subscription.current = documentStore
.listenQuery(query, queryParams ?? {}, {apiVersion: `v2022-05-09`})
.pipe(
catchError((err) => {
console.error(err)
setError(err)
setLoading(false)
setData(null)
})
)
.subscribe((documents) => {
setData(documents)
setLoading(false)
setError(false)
})
return () => (subscription.current?.unsubscribe ? subscription.current.unsubscribe() : null)
}
}, [query, queryParams])
return {loading, error, data} as ReturnShape
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment