|
| 1 | +import * as React from 'react' |
| 2 | +import { QueryClient, useInfiniteQuery } from '@tanstack/react-query' |
| 3 | +import { search } from './algolia' |
| 4 | + |
| 5 | +// Since the `cacheTime` property is string literal and not computed, the codemod should change it. |
| 6 | +export type UseAlgoliaOptionsButWithStringLiterals = { |
| 7 | + 'indexName': string |
| 8 | + 'query': string |
| 9 | + 'hitsPerPage'?: number |
| 10 | + 'staleTime'?: number |
| 11 | + 'cacheTime'?: number |
| 12 | + 'enabled'?: boolean |
| 13 | +} |
| 14 | + |
| 15 | +// Since the `cacheTime` property is an identifier and not computed, the codemod should change it. |
| 16 | +export type UseAlgoliaOptions = { |
| 17 | + indexName: string |
| 18 | + query: string |
| 19 | + hitsPerPage?: number |
| 20 | + staleTime?: number |
| 21 | + cacheTime?: number |
| 22 | + enabled?: boolean |
| 23 | +} |
| 24 | + |
| 25 | +// Since the `cacheTime` property is an identifier and not computed, and shorthand, the codemod should change it. |
| 26 | +export function useAlgolia<TData>({ |
| 27 | + indexName, |
| 28 | + query, |
| 29 | + hitsPerPage = 10, |
| 30 | + staleTime, |
| 31 | + cacheTime, |
| 32 | + enabled, |
| 33 | +}: UseAlgoliaOptions) { |
| 34 | + const queryInfo = useInfiniteQuery({ |
| 35 | + queryKey: ['algolia', indexName, query, hitsPerPage], |
| 36 | + queryFn: ({ pageParam }) => |
| 37 | + search<TData>({ indexName, query, pageParam, hitsPerPage }), |
| 38 | + defaultPageParam: 0, |
| 39 | + getNextPageParam: (lastPage) => lastPage?.nextPage, |
| 40 | + staleTime, |
| 41 | + cacheTime, |
| 42 | + enabled, |
| 43 | + }) |
| 44 | + |
| 45 | + const hits = queryInfo.data?.pages.map((page) => page.hits).flat() |
| 46 | + |
| 47 | + return { ...queryInfo, hits } |
| 48 | +} |
| 49 | + |
| 50 | +// Since the `cacheTime` property is an identifier and not computed, the codemod should change it. |
| 51 | +export const asIdentifierExample = () => |
| 52 | + new QueryClient({ |
| 53 | + defaultOptions: { |
| 54 | + queries: { |
| 55 | + cacheTime: 1000 * 60 * 60 * 24, // 24 hours |
| 56 | + }, |
| 57 | + }, |
| 58 | + }) |
| 59 | + |
| 60 | +// Since the `cacheTime` property is a string literal and not computed, the codemod should change it. |
| 61 | +export const asStringLiteralExample = () => |
| 62 | + new QueryClient({ |
| 63 | + defaultOptions: { |
| 64 | + queries: { |
| 65 | + 'cacheTime': 1000 * 60 * 60 * 24, // 24 hours |
| 66 | + }, |
| 67 | + }, |
| 68 | + }) |
| 69 | + |
| 70 | +// Since the `cacheTime` property is computed, the codemod shouldn't touch this example. |
| 71 | +export const asComputedExample = () => { |
| 72 | + const cacheTime = 'foo' |
| 73 | + |
| 74 | + return new QueryClient({ |
| 75 | + defaultOptions: { |
| 76 | + queries: { |
| 77 | + [cacheTime]: 1000 * 60 * 60 * 24, // 24 hours |
| 78 | + }, |
| 79 | + }, |
| 80 | + }) |
| 81 | +} |
0 commit comments