Last active
November 30, 2022 05:59
-
-
Save SimeonGriggs/ee7a3fb212625bf39d210f311642eb7e to your computer and use it in GitHub Desktop.
A custom hook for making and listening to document changes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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