Skip to content

Commit

Permalink
Apply React-query migration following the package upgrade
Browse files Browse the repository at this point in the history
  • Loading branch information
dtrucs committed Jul 16, 2024
1 parent b51363d commit 1bd6a93
Show file tree
Hide file tree
Showing 27 changed files with 343 additions and 287 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ const { activityBar } = getHomePageConfig();

export const useActivitySearchFilter = () => {
const language = useRouter().locale ?? getDefaultLanguage();
const { data: activities } = useQuery<ActivityFilter[], Error>(['homeActivities', language], () =>
getActivityBarContent(language, activityBar.links),
);
const { data: activities } = useQuery<ActivityFilter[], Error>({
queryKey: ['homeActivities', language],

queryFn: () => getActivityBarContent(language, activityBar.links),
});

const [expandedState, setExpandedState] = useState<'EXPANDED' | 'COLLAPSED'>('COLLAPSED');

Expand Down
12 changes: 5 additions & 7 deletions frontend/src/components/Footer/useFooter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,11 @@ export const useFooter = (): { config: FooterConfigOutput; intl: IntlShape } =>
const language = useRouter().locale ?? getDefaultLanguage();
const containsInformationIDLinks = links.some(link => 'informationID' in link);

const { data = [] } = useQuery<MenuItem[], Error>(
['footer', language],
() => getFlatPages(language),
{
enabled: containsInformationIDLinks,
},
);
const { data = [] } = useQuery<MenuItem[], Error>({
queryKey: ['footer', language],
queryFn: () => getFlatPages(language),
enabled: containsInformationIDLinks,
});
let nextLinks;
// If the footer config contains `informationID` keys,the app retrieves "flatpages" to get the corresponding label/url
if (containsInformationIDLinks === true) {
Expand Down
20 changes: 11 additions & 9 deletions frontend/src/components/Header/useHeader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,22 +15,24 @@ export const useHeader = (menuNode: MutableRefObject<HTMLDivElement | null | und
const config = getHeaderConfig();
const language = useRouter().locale ?? getDefaultLanguage();

const { data: currentAPIVersion } = useQuery(['APIVersion'], getAPIVersion);
const { data: currentAPIVersion } = useQuery({
queryKey: ['APIVersion'],
queryFn: getAPIVersion,
});

const is2_104LowerOrEqualCurrentAPIVersion = isLowerOrEqualCurrentAPIVersion(
'2.104.0',
currentAPIVersion,
);

// Call MenuItems or flatpage as fallback for GTA API Version below 2.104
const { data: menuItems } = useQuery<MenuItem[], Error>(
['header', language],
() => (is2_104LowerOrEqualCurrentAPIVersion ? geMenuItems(language) : getFlatPages(language)),
{
enabled: is2_104LowerOrEqualCurrentAPIVersion !== null,
staleTime: ONE_DAY,
},
);
const { data: menuItems } = useQuery<MenuItem[], Error>({
queryKey: ['header', language],
queryFn: () =>
is2_104LowerOrEqualCurrentAPIVersion ? geMenuItems(language) : getFlatPages(language),
enabled: is2_104LowerOrEqualCurrentAPIVersion !== null,
staleTime: ONE_DAY,
});
const intl = useIntl();

const { height = 0 } = useSize(menuNode) ?? {};
Expand Down
10 changes: 5 additions & 5 deletions frontend/src/components/Map/hooks/usePopupResult.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ export const usePopupResult = (id: string, shouldFetch: boolean, type: ContentTy
throw new Error('Incorrect type');
};

const { data: trekPopupResult, isLoading } = useQuery<PopupResult, Error>(
['popupResult', id, language],
fetchData,
{ enabled: type !== null && shouldFetch && commonDictionaries !== undefined },
);
const { data: trekPopupResult, isLoading } = useQuery<PopupResult, Error>({
queryKey: ['popupResult', id, language],
queryFn: fetchData,
enabled: type !== null && shouldFetch && commonDictionaries !== undefined,
});

return {
trekPopupResult,
Expand Down
8 changes: 4 additions & 4 deletions frontend/src/components/Map/hooks/useTrekGeometry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ export const useObjectGeometry = (
return getTouristicContentGeometryResult;
};

const { data: trekGeometry } = useQuery<GeometryObject, Error>(
['trekPopupResult', id, language],
() => func()(String(id), language),
);
const { data: trekGeometry } = useQuery<GeometryObject, Error>({
queryKey: ['trekPopupResult', id, language],
queryFn: () => func()(String(id), language),
});

return { trekGeometry };
};
37 changes: 12 additions & 25 deletions frontend/src/components/pages/details/useDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,8 @@ import { Details, TrekFamily } from 'modules/details/interface';
import { getDetails, getTrekFamily } from 'modules/details/connector';
import { isUrlString } from 'modules/utils/string';
import { ONE_DAY } from 'services/constants/staleTime';
import { isRessourceMissing } from 'services/routeUtils';
import { useCallback, useEffect, useState } from 'react';
import { useIntl } from 'react-intl';
import { useRouter } from 'next/router';
import { routes } from 'services/routes';
import { useMediaPredicate } from 'react-media-hook';
import useSectionsReferences from 'hooks/useSectionsReferences';
import { useQueryCommonDictionaries } from 'modules/dictionaries/api';
Expand Down Expand Up @@ -43,39 +40,29 @@ export const useDetails = (
) => {
const id = isUrlString(slug) ? slug.split('-')[0] : '';
const path = isUrlString(slug) ? decodeURI(slug) : '';
const router = useRouter();

const commonDictionaries = useQueryCommonDictionaries(language);

const {
data: details,
refetch,
isLoading,
} = useQuery<Details, Error>(
['details', id, language],
() => getDetails(id, language, commonDictionaries),
{
enabled: isUrlString(slug) && commonDictionaries !== undefined,
onError: error => {
if (isRessourceMissing(error)) {
void router.push(routes.HOME);
}
},
staleTime: ONE_DAY,
},
);
} = useQuery<Details, Error>({
queryKey: ['details', id, language],
queryFn: () => getDetails(id, language, commonDictionaries),
enabled: isUrlString(slug) && commonDictionaries !== undefined,
staleTime: ONE_DAY,
});

const isMobile = useMediaPredicate('(max-width: 1024px)');

const parentIdString = isUrlString(parentId) ? parentId : '';
const { data: trekFamily } = useQuery<TrekFamily | null, Error>(
['trekFamily', parentIdString, language],
() => getTrekFamily(isUrlString(parentId) ? parentId : '', language),
{
enabled: isUrlString(parentId),
staleTime: ONE_DAY,
},
);
const { data: trekFamily } = useQuery<TrekFamily | null, Error>({
queryKey: ['trekFamily', parentIdString, language],
queryFn: () => getTrekFamily(isUrlString(parentId) ? parentId : '', language),
enabled: isUrlString(parentId),
staleTime: ONE_DAY,
});

const { sections } = getDetailsConfig(language);

Expand Down
24 changes: 11 additions & 13 deletions frontend/src/components/pages/flatPage/useFlatPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,25 +22,23 @@ export const useFlatPage = (flatPageUrl: string | undefined) => {
refetch,
isLoading,
error,
} = useQuery<FlatPageDetails, Error>(
['flatPageDetails', id, language],
() => getFlatPageDetails(id, language, commonDictionaries),
{
enabled: isUrlString(flatPageUrl) && commonDictionaries !== undefined,
staleTime: ONE_DAY,
},
);
} = useQuery<FlatPageDetails, Error>({
queryKey: ['flatPageDetails', id, language],
queryFn: () => getFlatPageDetails(id, language, commonDictionaries),
enabled: isUrlString(flatPageUrl) && commonDictionaries !== undefined,
staleTime: ONE_DAY,
});
const suggestions = getSuggestionsFromContent(flatPage?.content ?? '');

const activitySuggestionIds = suggestions.flatMap(suggestion =>
'ids' in suggestion ? suggestion.ids : [suggestion.type],
);

const { data: activitySuggestions = [] } = useQuery<ActivitySuggestion[] | [], Error>(
['activitySuggestions', ...activitySuggestionIds, id, language],
() => getActivitySuggestions(suggestions, language, commonDictionaries),
{ enabled: suggestions.length > 0 && commonDictionaries !== undefined },
);
const { data: activitySuggestions = [] } = useQuery<ActivitySuggestion[] | [], Error>({
queryKey: ['activitySuggestions', ...activitySuggestionIds, id, language],
queryFn: () => getActivitySuggestions(suggestions, language, commonDictionaries),
enabled: suggestions.length > 0 && commonDictionaries !== undefined,
});

return {
id,
Expand Down
10 changes: 5 additions & 5 deletions frontend/src/components/pages/home/useHome.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ export const useHome = (): UseHome => {

const commonDictionaries = useQueryCommonDictionaries(language);

const { data = [] } = useQuery<ActivitySuggestion[] | [], Error>(
['activitySuggestions', `Suggestion-${activitySuggestionIds.join('-')}`, language],
() => getActivitySuggestions(suggestions, language, commonDictionaries),
{ enabled: suggestions.length > 0 && commonDictionaries !== undefined },
);
const { data = [] } = useQuery<ActivitySuggestion[] | [], Error>({
queryKey: ['activitySuggestions', `Suggestion-${activitySuggestionIds.join('-')}`, language],
queryFn: () => getActivitySuggestions(suggestions, language, commonDictionaries),
enabled: suggestions.length > 0 && commonDictionaries !== undefined,
});

return { config: homePageConfig, suggestions: data };
};
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ import { FormattedMessage } from 'react-intl';
export const useFilterBar = () => {
const { groupTreksAndOutdoorFilters, enableOutdoor } = getGlobalConfig();

const { data: currentAPIVersion } = useQuery<APIVersion | undefined>(
['APIVersion'],
getAPIVersion,
);
const { data: currentAPIVersion } = useQuery<APIVersion | undefined>({
queryKey: ['APIVersion'],
queryFn: getAPIVersion,
});

const is2_108LowerOrEqualCurrentAPIVersion = isLowerOrEqualCurrentAPIVersion(
'2.108.0',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ export const useFilter = () => {
organizerEvent: FilterWithoutType | null;
},
Error
>(['initialFilterState', language], () => getInitialFilters(language, initialOptions));
>({
queryKey: ['initialFilterState', language],
queryFn: () => getInitialFilters(language, initialOptions),
});

const initialFiltersState = data ? data.initialFiltersState : [];
const touristicContentCategoryMapping = data ? data.touristicContentCategoryMapping : {};
Expand Down
16 changes: 7 additions & 9 deletions frontend/src/components/pages/search/hooks/useCounter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ interface CountResult {
const useCounter = ({ language }: Args): CountResult => {
const commonDictionaries = useQueryCommonDictionaries(language);

const result = useQuery(
['counter'],
({
const result = useQuery({
queryKey: ['counter'],
queryFn: ({
pageParam = {
treks: 1,
touristicContents: 1,
Expand All @@ -40,12 +40,10 @@ const useCounter = ({ language }: Args): CountResult => {
language,
commonDictionaries,
),
{
refetchOnReconnect: false,
refetchOnWindowFocus: false,
staleTime: ONE_DAY,
},
);
refetchOnReconnect: false,
refetchOnWindowFocus: false,
staleTime: ONE_DAY,
});

return {
treksCount: result?.data?.resultsNumberDetails?.treksCount ?? 0,
Expand Down
14 changes: 10 additions & 4 deletions frontend/src/components/pages/search/hooks/useMapResults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,17 @@ export const useMapResults = (

const parsedFiltersState = parseFilters(filtersState);

const { data: mapResults, isLoading: isMapLoading } = useQuery<MapResults, Error>(
['mapResults', parsedFiltersState, language, parseTextFilter(textFilterState), dateFilter],
() =>
const { data: mapResults, isLoading: isMapLoading } = useQuery<MapResults, Error>({
queryKey: [
'mapResults',
parsedFiltersState,
language,
parseTextFilter(textFilterState),
dateFilter,
],
queryFn: () =>
getMapResults({ filtersState: parsedFiltersState, textFilterState, dateFilter }, language),
);
});

return {
isMapLoading,
Expand Down
53 changes: 26 additions & 27 deletions frontend/src/components/pages/search/hooks/useTrekResults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ export const useTrekResults = (
hasNextPage,
hasPreviousPage,
isFetchingNextPage,
} = useInfiniteQuery<SearchResults, Error>(
[
} = useInfiniteQuery<SearchResults, Error>({
queryKey: [
'trekResults',
JSON.stringify(parsedFiltersState),
language,
Expand All @@ -87,7 +87,7 @@ export const useTrekResults = (
JSON.stringify(dateFilter),
page,
],
({
queryFn: ({
pageParam = {
treks: page,
touristicContents: page,
Expand All @@ -102,30 +102,29 @@ export const useTrekResults = (
commonDictionaries,
);
},
{
retry: false,
// We already have a fallback component to allow the user to refetch
// Leaving these on induced issues with our refetching only next page strategy
// When it refetched on reconnect/focus the infinite scroll then stopped working
refetchOnReconnect: false,
refetchOnWindowFocus: false,
// hasNextPage will be set to false if getNextPageParam returns undefined
getNextPageParam: lastPageResult =>
lastPageResult.nextPages.treks !== null ||
lastPageResult.nextPages.touristicContents !== null ||
lastPageResult.nextPages.outdoorSites !== null ||
lastPageResult.nextPages.touristicEvents !== null
? lastPageResult.nextPages
: undefined,
getPreviousPageParam: lastPageResult =>
lastPageResult.previousPages.treks !== null ||
lastPageResult.previousPages.touristicContents !== null ||
lastPageResult.previousPages.outdoorSites !== null ||
lastPageResult.previousPages.touristicEvents !== null
? lastPageResult.previousPages
: undefined,
},
);
initialPageParam: page,
retry: false,
// We already have a fallback component to allow the user to refetch
// Leaving these on induced issues with our refetching only next page strategy
// When it refetched on reconnect/focus the infinite scroll then stopped working
refetchOnReconnect: false,
refetchOnWindowFocus: false,
// hasNextPage will be set to false if getNextPageParam returns undefined
getNextPageParam: lastPageResult =>
lastPageResult.nextPages.treks !== null ||
lastPageResult.nextPages.touristicContents !== null ||
lastPageResult.nextPages.outdoorSites !== null ||
lastPageResult.nextPages.touristicEvents !== null
? lastPageResult.nextPages
: undefined,
getPreviousPageParam: lastPageResult =>
lastPageResult.previousPages.treks !== null ||
lastPageResult.previousPages.touristicContents !== null ||
lastPageResult.previousPages.outdoorSites !== null ||
lastPageResult.previousPages.touristicEvents !== null
? lastPageResult.previousPages
: undefined,
});

useEffect(() => {
const url = computeUrl(filtersState, textFilterState, dateFilter);
Expand Down
Loading

0 comments on commit 1bd6a93

Please sign in to comment.