Last active
March 18, 2022 16:39
-
-
Save dr-skot/4d9fe9d71976ea50d89feddbf731d664 to your computer and use it in GitHub Desktop.
workaround for an issue with @parse/react-ssr 0.0.1.alpha-17 (https://github.com/parse-community/parse-react/issues/81)
This file contains 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 { EncodedParseQuery, useParseQuery } from '@parse/react-ssr'; | |
import usePrevious from '@/hooks/usePrevious'; | |
import { useEffect, useMemo, useRef, useState } from 'react'; | |
import { UseParseQueryResult } from '@parse/react-base'; | |
// this is a workaround for | |
// https://github.com/parse-community/parse-react/issues/81 | |
const useParseQuerySafer: typeof useParseQuery = (query, options) => { | |
const didntSyncYet = useRef(false); | |
// watch for query change | |
const queryString = getQueryString(query); | |
const queryIsNew = queryString !== usePrevious(queryString); | |
// use the same query object until the query string changes | |
const memoizedQuery = useMemo(() => query, [queryString]); | |
let response = useParseQuery(memoizedQuery, options); | |
// return correct first response to new query | |
if (queryIsNew && !response.error) | |
response = { | |
...response, | |
results: undefined, | |
isLoading: true, | |
isLive: false, | |
isSyncing: false, | |
}; | |
// fix delayed setting of isSyncing flag | |
if (queryIsNew) didntSyncYet.current = true; | |
else if (response.isSyncing) didntSyncYet.current = false; | |
const { isLoading, isLive } = response; | |
if (didntSyncYet.current && isLive && !isLoading) response.isSyncing = true; | |
return response; | |
}; | |
export default useParseQuerySafer; | |
// convert query to string so you can compare queries by value | |
function getQueryString(query: EncodedParseQuery | Parse.Query) { | |
const encoded = { | |
className: query.className, | |
query: query instanceof Parse.Query ? query.toJSON() : query.query, | |
}; | |
return JSON.stringify(encoded); | |
} |
Author
dr-skot
commented
Mar 14, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment