From 07c1693eaf985ef47512a2b8753b0f1e75e8c1d1 Mon Sep 17 00:00:00 2001 From: Sinclair Chen Date: Thu, 8 Sep 2022 12:47:44 -0700 Subject: [PATCH] Cache with react query instead of memoize --- web/components/editor/mention-suggestion.ts | 11 +++++------ web/hooks/use-users.ts | 7 ++++++- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/web/components/editor/mention-suggestion.ts b/web/components/editor/mention-suggestion.ts index 583509b2..9f016d47 100644 --- a/web/components/editor/mention-suggestion.ts +++ b/web/components/editor/mention-suggestion.ts @@ -1,16 +1,13 @@ import type { MentionOptions } from '@tiptap/extension-mention' import { ReactRenderer } from '@tiptap/react' import { searchInAny } from 'common/util/parse' -import { memoize, orderBy } from 'lodash' +import { orderBy } from 'lodash' import tippy from 'tippy.js' -import { getUsers } from 'web/lib/firebase/users' +import { getCachedUsers } from 'web/hooks/use-users' import { MentionList } from './mention-list' type Suggestion = MentionOptions['suggestion'] -const users = memoize(getUsers) -users() // prefetch - const beginsWith = (text: string, query: string) => text.toLocaleLowerCase().startsWith(query.toLocaleLowerCase()) @@ -18,7 +15,9 @@ const beginsWith = (text: string, query: string) => export const mentionSuggestion: Suggestion = { items: async ({ query }) => orderBy( - (await users()).filter((u) => searchInAny(query, u.username, u.name)), + (await getCachedUsers()).filter((u) => + searchInAny(query, u.username, u.name) + ), [ (u) => [u.name, u.username].some((s) => beginsWith(s, query)), 'followerCountCached', diff --git a/web/hooks/use-users.ts b/web/hooks/use-users.ts index 659395b8..330b9c1d 100644 --- a/web/hooks/use-users.ts +++ b/web/hooks/use-users.ts @@ -6,7 +6,8 @@ import { useFollows } from './use-follows' import { useUser } from './use-user' import { useFirestoreQueryData } from '@react-query-firebase/firestore' import { DocumentData } from 'firebase/firestore' -import { users, privateUsers } from 'web/lib/firebase/users' +import { users, privateUsers, getUsers } from 'web/lib/firebase/users' +import { QueryClient } from 'react-query' export const useUsers = () => { const result = useFirestoreQueryData(['users'], users, { @@ -16,6 +17,10 @@ export const useUsers = () => { return result.data ?? [] } +const q = new QueryClient() +export const getCachedUsers = async () => + q.fetchQuery(['users'], getUsers, { staleTime: Infinity }) + export const usePrivateUsers = () => { const result = useFirestoreQueryData( ['private users'],