From 75edb7a663934c7dd68f9d766b7b38ca2793076f Mon Sep 17 00:00:00 2001 From: Soapbox Bot Date: Tue, 17 Oct 2023 15:05:15 +0000 Subject: [PATCH 1/2] Update dependency @tanstack/react-query to v5 --- package.json | 2 +- yarn.lock | 22 ++++++++++------------ 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/package.json b/package.json index a7812efb6..30d7c2fbb 100644 --- a/package.json +++ b/package.json @@ -70,7 +70,7 @@ "@tailwindcss/aspect-ratio": "^0.4.2", "@tailwindcss/forms": "^0.5.3", "@tailwindcss/typography": "^0.5.9", - "@tanstack/react-query": "^4.0.10", + "@tanstack/react-query": "^5.0.0", "@types/escape-html": "^1.0.1", "@types/http-link-header": "^1.0.3", "@types/leaflet": "^1.8.0", diff --git a/yarn.lock b/yarn.lock index dcddc388f..27f9a4821 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2134,19 +2134,17 @@ lodash.merge "^4.6.2" postcss-selector-parser "6.0.10" -"@tanstack/query-core@^4.0.0-beta.1": - version "4.0.10" - resolved "https://registry.yarnpkg.com/@tanstack/query-core/-/query-core-4.0.10.tgz#cae6f818006616dc72c95c863592f5f68b47548a" - integrity sha512-9LsABpZXkWZHi4P1ozRETEDXQocLAxVzQaIhganxbNuz/uA3PsCAJxJTiQrknG5htLMzOF5MqM9G10e6DCxV1A== +"@tanstack/query-core@5.0.0": + version "5.0.0" + resolved "https://registry.yarnpkg.com/@tanstack/query-core/-/query-core-5.0.0.tgz#b37a50bb3a4f54336b6131db00b72cd29e79b480" + integrity sha512-Y1BpiA6BblJd/UlVqxEVeAG7IACn568YJuTTItAiecBI7En+33g780kg+/8lhgl+BzcUPN7o+NjBrSRGJoemyQ== -"@tanstack/react-query@^4.0.10": - version "4.0.10" - resolved "https://registry.yarnpkg.com/@tanstack/react-query/-/react-query-4.0.10.tgz#92c71a2632c06450d848d4964959bd216cde03c0" - integrity sha512-Wn5QhZUE5wvr6rGClV7KeQIUsdTmYR9mgmMZen7DSRWauHW2UTynFg3Kkf6pw+XlxxOLsyLWwz/Q6q1lSpM3TQ== +"@tanstack/react-query@^5.0.0": + version "5.0.0" + resolved "https://registry.yarnpkg.com/@tanstack/react-query/-/react-query-5.0.0.tgz#707fecb71cf53ae098f682f45520d7b1640bcaa9" + integrity sha512-diQoC8FNBcO5Uf5yuaJlXthTtbO1xM8kzOX+pSBUMT9n/cqQ/u1wJGCtukvhDWA+6j07WmIj4bfqNbd2KOB6jQ== dependencies: - "@tanstack/query-core" "^4.0.0-beta.1" - "@types/use-sync-external-store" "^0.0.3" - use-sync-external-store "^1.2.0" + "@tanstack/query-core" "5.0.0" "@testing-library/dom@^9.0.0": version "9.0.1" @@ -8739,7 +8737,7 @@ url-parse@^1.5.3: querystringify "^2.1.1" requires-port "^1.0.0" -use-sync-external-store@^1.0.0, use-sync-external-store@^1.2.0: +use-sync-external-store@^1.0.0: version "1.2.0" resolved "https://registry.yarnpkg.com/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz#7dbefd6ef3fe4e767a0cf5d7287aacfb5846928a" integrity sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA== From 19ab202737afda447d129098c1df69877aa64dc5 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 17 Oct 2023 15:19:05 -0500 Subject: [PATCH 2/2] Update code to new react-query API --- src/actions/streaming.ts | 4 +- src/api/hooks/groups/useGroupValidation.ts | 4 +- src/features/account/components/header.tsx | 11 +- .../components/chat-message-list-intro.tsx | 2 +- .../chats/components/chat-message.tsx | 7 +- .../components/chat-page-settings.tsx | 2 +- .../chat-page/components/welcome.tsx | 2 +- .../components/chat-search/chat-search.tsx | 7 +- src/features/chats/components/chat.tsx | 2 +- src/queries/__mocks__/client.ts | 8 +- src/queries/accounts.ts | 3 +- src/queries/chats.ts | 174 ++++++++++-------- src/queries/client.ts | 2 +- src/queries/embed.ts | 5 +- src/queries/relationships.ts | 9 +- src/queries/search.ts | 9 +- src/queries/suggestions.ts | 36 ++-- src/queries/trends.ts | 4 +- src/utils/chats.ts | 4 +- src/utils/queries.ts | 4 +- 20 files changed, 164 insertions(+), 135 deletions(-) diff --git a/src/actions/streaming.ts b/src/actions/streaming.ts index 9557757ae..2c6603bef 100644 --- a/src/actions/streaming.ts +++ b/src/actions/streaming.ts @@ -43,7 +43,9 @@ const removeChatMessage = (payload: string) => { // If the user just deleted the "last_message", then let's invalidate // the Chat Search query so the Chat List will show the new "last_message". if (isLastMessage(chatMessageId)) { - queryClient.invalidateQueries(ChatKeys.chatSearch()); + queryClient.invalidateQueries({ + queryKey: ChatKeys.chatSearch(), + }); } removePageItem(ChatKeys.chatMessages(chatId), chatMessageId, (o: any, n: any) => String(o.id) === String(n)); diff --git a/src/api/hooks/groups/useGroupValidation.ts b/src/api/hooks/groups/useGroupValidation.ts index ffa35eb6f..cc1062ccc 100644 --- a/src/api/hooks/groups/useGroupValidation.ts +++ b/src/api/hooks/groups/useGroupValidation.ts @@ -31,7 +31,9 @@ function useGroupValidation(name: string = '') { return data; }; - const queryInfo = useQuery(ValidationKeys.validation(name), getValidation, { + const queryInfo = useQuery({ + queryKey: ValidationKeys.validation(name), + queryFn: getValidation, enabled: features.groupsValidation && !!name, }); diff --git a/src/features/account/components/header.tsx b/src/features/account/components/header.tsx index 99321cb40..21c4b51d0 100644 --- a/src/features/account/components/header.tsx +++ b/src/features/account/components/header.tsx @@ -92,16 +92,17 @@ const Header: React.FC = ({ account }) => { const { getOrCreateChatByAccountId } = useChats(); - const createAndNavigateToChat = useMutation((accountId: string) => { - return getOrCreateChatByAccountId(accountId); - }, { + const createAndNavigateToChat = useMutation({ + mutationFn: (accountId: string) => getOrCreateChatByAccountId(accountId), onError: (error: AxiosError) => { const data = error.response?.data as any; toast.error(data?.error); }, onSuccess: (response) => { history.push(`/chats/${response.data.id}`); - queryClient.invalidateQueries(ChatKeys.chatSearch()); + queryClient.invalidateQueries({ + queryKey: ChatKeys.chatSearch(), + }); }, }); @@ -571,7 +572,7 @@ const Header: React.FC = ({ account }) => { theme='outlined' className='px-2' iconClassName='h-4 w-4' - disabled={createAndNavigateToChat.isLoading} + disabled={createAndNavigateToChat.isPending} /> ); } else if (account.pleroma?.accepts_chat_messages) { diff --git a/src/features/chats/components/chat-message-list-intro.tsx b/src/features/chats/components/chat-message-list-intro.tsx index 3e63be246..b63bea5e9 100644 --- a/src/features/chats/components/chat-message-list-intro.tsx +++ b/src/features/chats/components/chat-message-list-intro.tsx @@ -92,7 +92,7 @@ const ChatMessageListIntro = () => { theme='primary' block onClick={() => acceptChat.mutate()} - disabled={acceptChat.isLoading} + disabled={acceptChat.isPending} > {intl.formatMessage(messages.accept)} diff --git a/src/features/chats/components/chat-message.tsx b/src/features/chats/components/chat-message.tsx index c4134a48b..124ce9e41 100644 --- a/src/features/chats/components/chat-message.tsx +++ b/src/features/chats/components/chat-message.tsx @@ -68,9 +68,12 @@ const ChatMessage = (props: IChatMessage) => { const [isReactionSelectorOpen, setIsReactionSelectorOpen] = useState(false); const [isMenuOpen, setIsMenuOpen] = useState(false); - const handleDeleteMessage = useMutation((chatMessageId: string) => deleteChatMessage(chatMessageId), { + const handleDeleteMessage = useMutation({ + mutationFn: (chatMessageId: string) => deleteChatMessage(chatMessageId), onSettled: () => { - queryClient.invalidateQueries(ChatKeys.chatMessages(chat.id)); + queryClient.invalidateQueries({ + queryKey: ChatKeys.chatMessages(chat.id), + }); }, }); diff --git a/src/features/chats/components/chat-page/components/chat-page-settings.tsx b/src/features/chats/components/chat-page/components/chat-page-settings.tsx index 404c56afd..cb637a36e 100644 --- a/src/features/chats/components/chat-page/components/chat-page-settings.tsx +++ b/src/features/chats/components/chat-page/components/chat-page-settings.tsx @@ -84,7 +84,7 @@ const ChatPageSettings = () => { - diff --git a/src/features/chats/components/chat-page/components/welcome.tsx b/src/features/chats/components/chat-page/components/welcome.tsx index ae9c351b2..f78de0e32 100644 --- a/src/features/chats/components/chat-page/components/welcome.tsx +++ b/src/features/chats/components/chat-page/components/welcome.tsx @@ -69,7 +69,7 @@ const Welcome = () => { {intl.formatMessage(messages.notice)} - diff --git a/src/features/chats/components/chat-search/chat-search.tsx b/src/features/chats/components/chat-search/chat-search.tsx index 82bd880f9..6f9b9c843 100644 --- a/src/features/chats/components/chat-search/chat-search.tsx +++ b/src/features/chats/components/chat-search/chat-search.tsx @@ -43,9 +43,8 @@ const ChatSearch = (props: IChatSearch) => { const hasSearchValue = debouncedValue && debouncedValue.length > 0; const hasSearchResults = (accounts || []).length > 0; - const handleClickOnSearchResult = useMutation((accountId: string) => { - return getOrCreateChatByAccountId(accountId); - }, { + const handleClickOnSearchResult = useMutation({ + mutationFn: (accountId: string) => getOrCreateChatByAccountId(accountId), onError: (error: AxiosError) => { const data = error.response?.data as any; toast.error(data?.error); @@ -57,7 +56,7 @@ const ChatSearch = (props: IChatSearch) => { changeScreen(ChatWidgetScreens.CHAT, response.data.id); } - queryClient.invalidateQueries(ChatKeys.chatSearch()); + queryClient.invalidateQueries({ queryKey: ChatKeys.chatSearch() }); }, }); diff --git a/src/features/chats/components/chat.tsx b/src/features/chats/components/chat.tsx index 6baffc100..627fe2972 100644 --- a/src/features/chats/components/chat.tsx +++ b/src/features/chats/components/chat.tsx @@ -93,7 +93,7 @@ const Chat: React.FC = ({ chat, inputRef, className }) => { }; const sendMessage = () => { - if (!isSubmitDisabled && !createChatMessage.isLoading) { + if (!isSubmitDisabled && !createChatMessage.isPending) { submitMessage(); if (!chat.accepted) { diff --git a/src/queries/__mocks__/client.ts b/src/queries/__mocks__/client.ts index ab9de8f4b..56123fd1d 100644 --- a/src/queries/__mocks__/client.ts +++ b/src/queries/__mocks__/client.ts @@ -1,16 +1,10 @@ import { QueryClient } from '@tanstack/react-query'; const queryClient = new QueryClient({ - logger: { - // eslint-disable-next-line no-console - log: console.log, - warn: console.warn, - error: () => { }, - }, defaultOptions: { queries: { staleTime: 0, - cacheTime: Infinity, + gcTime: Infinity, retry: false, }, }, diff --git a/src/queries/accounts.ts b/src/queries/accounts.ts index b7ee6d1eb..06b7cb514 100644 --- a/src/queries/accounts.ts +++ b/src/queries/accounts.ts @@ -39,7 +39,8 @@ const useUpdateCredentials = () => { const api = useApi(); const dispatch = useAppDispatch(); - return useMutation((data: UpdateCredentialsData) => api.patch('/api/v1/accounts/update_credentials', data), { + return useMutation({ + mutationFn: (data: UpdateCredentialsData) => api.patch('/api/v1/accounts/update_credentials', data), onMutate(variables) { const cachedAccount = account; dispatch(patchMeSuccess({ ...account, ...variables })); diff --git a/src/queries/chats.ts b/src/queries/chats.ts index 8c9a4de40..8bf382900 100644 --- a/src/queries/chats.ts +++ b/src/queries/chats.ts @@ -1,4 +1,4 @@ -import { InfiniteData, useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query'; +import { InfiniteData, keepPreviousData, useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query'; import sumBy from 'lodash/sumBy'; import { importFetchedAccount, importFetchedAccounts } from 'soapbox/actions/importer'; @@ -98,10 +98,13 @@ const useChatMessages = (chat: IChat) => { }; }; - const queryInfo = useInfiniteQuery(ChatKeys.chatMessages(chat.id), ({ pageParam }) => getChatMessages(chat.id, pageParam), { + const queryInfo = useInfiniteQuery({ + queryKey: ChatKeys.chatMessages(chat.id), + queryFn: ({ pageParam }) => getChatMessages(chat.id, pageParam), enabled: !isBlocked, - cacheTime: 0, + gcTime: 0, staleTime: 0, + initialPageParam: { link: undefined as string | undefined }, getNextPageParam: (config) => { if (config.hasMore) { return { link: config.link }; @@ -153,9 +156,12 @@ const useChats = (search?: string) => { }; }; - const queryInfo = useInfiniteQuery(ChatKeys.chatSearch(search), ({ pageParam }) => getChats(pageParam), { - keepPreviousData: true, + const queryInfo = useInfiniteQuery({ + queryKey: ChatKeys.chatSearch(search), + queryFn: ({ pageParam }) => getChats(pageParam), + placeholderData: keepPreviousData, enabled: features.chats, + initialPageParam: { link: undefined as string | undefined }, getNextPageParam: (config) => { if (config.hasMore) { return { link: config.link }; @@ -193,8 +199,10 @@ const useChat = (chatId?: string) => { } }; - return useQuery(ChatKeys.chat(chatId), getChat, { - cacheTime: 0, + return useQuery({ + queryKey: ChatKeys.chat(chatId), + queryFn: getChat, + gcTime: 0, enabled: !!chatId, }); }; @@ -230,75 +238,78 @@ const useChatActions = (chatId: string) => { .catch(() => null); }; - const createChatMessage = useMutation( - ({ chatId, content, mediaIds }: { chatId: string; content: string; mediaIds?: string[] }) => { + const createChatMessage = useMutation({ + mutationFn: ({ chatId, content, mediaIds }: { chatId: string; content: string; mediaIds?: string[] }) => { return api.post(`/api/v1/pleroma/chats/${chatId}/messages`, { content, media_id: (mediaIds && mediaIds.length === 1) ? mediaIds[0] : undefined, // Pleroma backwards-compat media_ids: mediaIds, }); }, - { - retry: false, - onMutate: async (variables) => { - // Cancel any outgoing refetches (so they don't overwrite our optimistic update) - await queryClient.cancelQueries(['chats', 'messages', variables.chatId]); + retry: false, + onMutate: async (variables) => { + // Cancel any outgoing refetches (so they don't overwrite our optimistic update) + await queryClient.cancelQueries({ + queryKey: ['chats', 'messages', variables.chatId], + }); - // Snapshot the previous value - const prevContent = variables.content; - const prevChatMessages = queryClient.getQueryData(['chats', 'messages', variables.chatId]); - const pendingId = String(Number(new Date())); + // Snapshot the previous value + const prevContent = variables.content; + const prevChatMessages = queryClient.getQueryData(['chats', 'messages', variables.chatId]); + const pendingId = String(Number(new Date())); - // Optimistically update to the new value - queryClient.setQueryData(ChatKeys.chatMessages(variables.chatId), (prevResult: any) => { - const newResult = { ...prevResult }; - newResult.pages = newResult.pages.map((page: any, idx: number) => { - if (idx === 0) { - return { - ...page, - result: [ - normalizeChatMessage({ - content: variables.content, - id: pendingId, - created_at: new Date(), - account_id: account?.id, - pending: true, - unread: true, - }), - ...page.result, - ], - }; - } + // Optimistically update to the new value + queryClient.setQueryData(ChatKeys.chatMessages(variables.chatId), (prevResult: any) => { + const newResult = { ...prevResult }; + newResult.pages = newResult.pages.map((page: any, idx: number) => { + if (idx === 0) { + return { + ...page, + result: [ + normalizeChatMessage({ + content: variables.content, + id: pendingId, + created_at: new Date(), + account_id: account?.id, + pending: true, + unread: true, + }), + ...page.result, + ], + }; + } - return page; - }); - - return newResult; + return page; }); - return { prevChatMessages, prevContent, pendingId }; - }, - // If the mutation fails, use the context returned from onMutate to roll back - onError: (_error: any, variables, context: any) => { - queryClient.setQueryData(['chats', 'messages', variables.chatId], context.prevChatMessages); - }, - onSuccess: (response: any, variables, context) => { - const nextChat = { ...chat, last_message: response.data }; - updatePageItem(ChatKeys.chatSearch(), nextChat, (o, n) => o.id === n.id); - updatePageItem( - ChatKeys.chatMessages(variables.chatId), - normalizeChatMessage(response.data), - (o) => o.id === context.pendingId, - ); - reOrderChatListItems(); - }, - }, - ); + return newResult; + }); - const updateChat = useMutation((data: UpdateChatVariables) => api.patch(`/api/v1/pleroma/chats/${chatId}`, data), { + return { prevChatMessages, prevContent, pendingId }; + }, + // If the mutation fails, use the context returned from onMutate to roll back + onError: (_error: any, variables, context: any) => { + queryClient.setQueryData(['chats', 'messages', variables.chatId], context.prevChatMessages); + }, + onSuccess: (response: any, variables, context) => { + const nextChat = { ...chat, last_message: response.data }; + updatePageItem(ChatKeys.chatSearch(), nextChat, (o, n) => o.id === n.id); + updatePageItem( + ChatKeys.chatMessages(variables.chatId), + normalizeChatMessage(response.data), + (o) => o.id === context.pendingId, + ); + reOrderChatListItems(); + }, + }); + + const updateChat = useMutation({ + mutationFn: (data: UpdateChatVariables) => api.patch(`/api/v1/pleroma/chats/${chatId}`, data), onMutate: async (data) => { // Cancel any outgoing refetches (so they don't overwrite our optimistic update) - await queryClient.cancelQueries(ChatKeys.chat(chatId)); + await queryClient.cancelQueries({ + queryKey: ChatKeys.chat(chatId), + }); // Snapshot the previous value const prevChat = { ...chat }; @@ -317,48 +328,49 @@ const useChatActions = (chatId: string) => { toast.error('Chat Settings failed to update.'); }, onSuccess() { - queryClient.invalidateQueries(ChatKeys.chat(chatId)); - queryClient.invalidateQueries(ChatKeys.chatSearch()); + queryClient.invalidateQueries({ queryKey: ChatKeys.chat(chatId) }); + queryClient.invalidateQueries({ queryKey: ChatKeys.chatSearch() }); toast.success('Chat Settings updated successfully'); }, }); const deleteChatMessage = (chatMessageId: string) => api.delete(`/api/v1/pleroma/chats/${chatId}/messages/${chatMessageId}`); - const acceptChat = useMutation(() => api.post(`/api/v1/pleroma/chats/${chatId}/accept`), { + const acceptChat = useMutation({ + mutationFn: () => api.post(`/api/v1/pleroma/chats/${chatId}/accept`), onSuccess(response) { changeScreen(ChatWidgetScreens.CHAT, response.data.id); - queryClient.invalidateQueries(ChatKeys.chat(chatId)); - queryClient.invalidateQueries(ChatKeys.chatMessages(chatId)); - queryClient.invalidateQueries(ChatKeys.chatSearch()); + queryClient.invalidateQueries({ queryKey: ChatKeys.chat(chatId) }); + queryClient.invalidateQueries({ queryKey: ChatKeys.chatMessages(chatId) }); + queryClient.invalidateQueries({ queryKey: ChatKeys.chatSearch() }); }, }); - const deleteChat = useMutation(() => api.delete(`/api/v1/pleroma/chats/${chatId}`), { + const deleteChat = useMutation({ + mutationFn: () => api.delete(`/api/v1/pleroma/chats/${chatId}`), onSuccess() { changeScreen(ChatWidgetScreens.INBOX); - queryClient.invalidateQueries(ChatKeys.chatMessages(chatId)); - queryClient.invalidateQueries(ChatKeys.chatSearch()); + queryClient.invalidateQueries({ queryKey: ChatKeys.chatMessages(chatId) }); + queryClient.invalidateQueries({ queryKey: ChatKeys.chatSearch() }); }, }); - const createReaction = useMutation((data: CreateReactionVariables) => api.post(`/api/v1/pleroma/chats/${chatId}/messages/${data.messageId}/reactions`, { - emoji: data.emoji, - }), { + const createReaction = useMutation({ + mutationFn: (data: CreateReactionVariables) => api.post(`/api/v1/pleroma/chats/${chatId}/messages/${data.messageId}/reactions`, { + emoji: data.emoji, + }), // TODO: add optimistic updates onSuccess(response) { updateChatMessage(response.data); }, }); - const deleteReaction = useMutation( - (data: CreateReactionVariables) => api.delete(`/api/v1/pleroma/chats/${chatId}/messages/${data.messageId}/reactions/${data.emoji}`), - { - onSuccess() { - queryClient.invalidateQueries(ChatKeys.chatMessages(chatId)); - }, + const deleteReaction = useMutation({ + mutationFn: (data: CreateReactionVariables) => api.delete(`/api/v1/pleroma/chats/${chatId}/messages/${data.messageId}/reactions/${data.emoji}`), + onSuccess() { + queryClient.invalidateQueries({ queryKey: ChatKeys.chatMessages(chatId) }); }, - ); + }); return { acceptChat, diff --git a/src/queries/client.ts b/src/queries/client.ts index a1b90ecf1..e11ce296c 100644 --- a/src/queries/client.ts +++ b/src/queries/client.ts @@ -5,7 +5,7 @@ const queryClient = new QueryClient({ queries: { refetchOnWindowFocus: false, staleTime: 60000, // 1 minute - cacheTime: Infinity, + gcTime: Infinity, retry: false, }, }, diff --git a/src/queries/embed.ts b/src/queries/embed.ts index 4ad2d1455..eb32618ef 100644 --- a/src/queries/embed.ts +++ b/src/queries/embed.ts @@ -26,5 +26,8 @@ export default function useEmbed(url: string) { return data; }; - return useQuery(['embed', url], getEmbed); + return useQuery({ + queryKey: ['embed', url], + queryFn: getEmbed, + }); } diff --git a/src/queries/relationships.ts b/src/queries/relationships.ts index bbe306d3c..e4b8d1188 100644 --- a/src/queries/relationships.ts +++ b/src/queries/relationships.ts @@ -8,11 +8,12 @@ const useFetchRelationships = () => { const api = useApi(); const dispatch = useAppDispatch(); - return useMutation(({ accountIds }: { accountIds: string[]}) => { - const ids = accountIds.map((id) => `id[]=${id}`).join('&'); + return useMutation({ + mutationFn: ({ accountIds }: { accountIds: string[]}) => { + const ids = accountIds.map((id) => `id[]=${id}`).join('&'); - return api.get(`/api/v1/accounts/relationships?${ids}`); - }, { + return api.get(`/api/v1/accounts/relationships?${ids}`); + }, onSuccess(response) { dispatch(fetchRelationshipsSuccess(response.data)); }, diff --git a/src/queries/search.ts b/src/queries/search.ts index 41c4b7fb3..6cbe2dfa9 100644 --- a/src/queries/search.ts +++ b/src/queries/search.ts @@ -1,4 +1,4 @@ -import { useInfiniteQuery } from '@tanstack/react-query'; +import { keepPreviousData, useInfiniteQuery } from '@tanstack/react-query'; import { getNextLink } from 'soapbox/api'; import { useApi } from 'soapbox/hooks'; @@ -31,8 +31,11 @@ export default function useAccountSearch(q: string) { }; }; - const queryInfo = useInfiniteQuery(['search', 'accounts', q], ({ pageParam }) => getAccountSearch(q, pageParam), { - keepPreviousData: true, + const queryInfo = useInfiniteQuery({ + queryKey: ['search', 'accounts', q], + queryFn: ({ pageParam }) => getAccountSearch(q, pageParam), + placeholderData: keepPreviousData, + initialPageParam: { link: undefined as string | undefined }, getNextPageParam: (config) => { if (config.hasMore) { return { link: config.link }; diff --git a/src/queries/suggestions.ts b/src/queries/suggestions.ts index eec236d6b..aa7fa5597 100644 --- a/src/queries/suggestions.ts +++ b/src/queries/suggestions.ts @@ -1,4 +1,4 @@ -import { useInfiniteQuery, useMutation } from '@tanstack/react-query'; +import { useInfiniteQuery, useMutation, keepPreviousData } from '@tanstack/react-query'; import { fetchRelationships } from 'soapbox/actions/accounts'; import { importFetchedAccounts } from 'soapbox/actions/importer'; @@ -48,19 +48,19 @@ const useSuggestions = () => { }; }; - const result = useInfiniteQuery( - SuggestionKeys.suggestions, - ({ pageParam }: any) => getV2Suggestions(pageParam), - { - keepPreviousData: true, - getNextPageParam: (config) => { - if (config?.hasMore) { - return { nextLink: config?.link }; - } + const result = useInfiniteQuery({ + queryKey: SuggestionKeys.suggestions, + queryFn: ({ pageParam }: any) => getV2Suggestions(pageParam), + placeholderData: keepPreviousData, + initialPageParam: { nextLink: undefined }, + getNextPageParam: (config) => { + if (config?.hasMore) { + return { nextLink: config?.link }; + } - return undefined; - }, - }); + return undefined; + }, + }); const data: any = result.data?.pages.reduce( (prev: any, curr: any) => [...prev, ...curr.result], @@ -76,7 +76,8 @@ const useSuggestions = () => { const useDismissSuggestion = () => { const api = useApi(); - return useMutation((accountId: string) => api.delete(`/api/v1/suggestions/${accountId}`), { + return useMutation({ + mutationFn: (accountId: string) => api.delete(`/api/v1/suggestions/${accountId}`), onMutate(accountId: string) { removePageItem(SuggestionKeys.suggestions, accountId, (o: any, n: any) => o.account === n); }, @@ -105,8 +106,11 @@ function useOnboardingSuggestions() { }; }; - const result = useInfiniteQuery(['suggestions', 'v2'], ({ pageParam }) => getV2Suggestions(pageParam), { - keepPreviousData: true, + const result = useInfiniteQuery({ + queryKey: ['suggestions', 'v2'], + queryFn: ({ pageParam }) => getV2Suggestions(pageParam), + placeholderData: keepPreviousData, + initialPageParam: { link: undefined as string | undefined }, getNextPageParam: (config) => { if (config.hasMore) { return { link: config.link }; diff --git a/src/queries/trends.ts b/src/queries/trends.ts index afe780991..cf46d130c 100644 --- a/src/queries/trends.ts +++ b/src/queries/trends.ts @@ -19,7 +19,9 @@ export default function useTrends() { return normalizedData; }; - const result = useQuery>(['trends'], getTrends, { + const result = useQuery>({ + queryKey: ['trends'], + queryFn: getTrends, placeholderData: [], staleTime: 600000, // 10 minutes }); diff --git a/src/utils/chats.ts b/src/utils/chats.ts index 8e8f7562f..423565e49 100644 --- a/src/utils/chats.ts +++ b/src/utils/chats.ts @@ -50,7 +50,9 @@ const checkIfChatExists = (chatId: string) => { * Force a re-fetch of ChatSearch. */ const invalidateChatSearchQuery = () => { - queryClient.invalidateQueries(ChatKeys.chatSearch()); + queryClient.invalidateQueries({ + queryKey: ChatKeys.chatSearch(), + }); }; const updateChatListItem = (newChat: ChatPayload) => { diff --git a/src/utils/queries.ts b/src/utils/queries.ts index f9428da11..5932b2135 100644 --- a/src/utils/queries.ts +++ b/src/utils/queries.ts @@ -41,7 +41,7 @@ const flattenPages = (queryData: InfiniteData> | undefined /** Traverse pages and update the item inside if found. */ const updatePageItem = (queryKey: QueryKey, newItem: T, isItem: (item: T, newItem: T) => boolean) => { - queryClient.setQueriesData>>(queryKey, (data) => { + queryClient.setQueriesData>>({ queryKey }, (data) => { if (data) { const pages = data.pages.map(page => { const result = page.result.map(item => isItem(item, newItem) ? newItem : item); @@ -65,7 +65,7 @@ const appendPageItem = (queryKey: QueryKey, newItem: T) => { /** Remove an item inside if found. */ const removePageItem = (queryKey: QueryKey, itemToRemove: T, isItem: (item: T, newItem: T) => boolean) => { - queryClient.setQueriesData>>(queryKey, (data) => { + queryClient.setQueriesData>>({ queryKey }, (data) => { if (data) { const pages = data.pages.map(page => { const result = page.result.filter(item => !isItem(item, itemToRemove));