-
Notifications
You must be signed in to change notification settings - Fork 2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Stats: add location views query hook (#97951)
* Add location views query * Implement useLocationViewsQuery hook * Normalize country views * Fix country views render * Remove 'useShortNumber' prop
- Loading branch information
Showing
2 changed files
with
76 additions
and
31 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import { useQuery } from '@tanstack/react-query'; | ||
import wpcom from 'calypso/lib/wp'; | ||
import { normalizers } from 'calypso/state/stats/lists/utils'; | ||
import getDefaultQueryParams from './default-query-params'; | ||
import { processQueryParams, QueryStatsParams } from './utils'; | ||
|
||
export interface StatsLocationViewsData { | ||
date: string; | ||
days?: Array< { date: string; views: Record< string, number > } >; | ||
summary?: Record< string, number >; | ||
countryInfo?: Record< string, unknown >; | ||
} | ||
|
||
function queryStatsLocationViews( | ||
siteId: number, | ||
geoMode: 'country' | 'region' | 'city', | ||
query: QueryStatsParams | ||
): Promise< StatsLocationViewsData > { | ||
return wpcom.req.get( `/sites/${ siteId }/stats/location-views/${ geoMode }`, query ); | ||
} | ||
|
||
const useLocationViewsQuery = < T = StatsLocationViewsData >( | ||
siteId: number, | ||
geoMode: 'country' | 'region' | 'city', | ||
query: QueryStatsParams | ||
) => { | ||
return useQuery( { | ||
...getDefaultQueryParams(), | ||
queryKey: [ 'stats', 'location-views', siteId, geoMode, query ], | ||
queryFn: () => | ||
queryStatsLocationViews( siteId, geoMode, processQueryParams( query ) ) as Promise< T >, | ||
select: ( data ) => { | ||
const normalizedStats = normalizers.statsCountryViews( | ||
data as StatsLocationViewsData, | ||
query | ||
); | ||
|
||
return Array.isArray( normalizedStats ) && normalizedStats?.length && query?.max | ||
? normalizedStats.slice( 0, query.max ) | ||
: normalizedStats; | ||
}, | ||
staleTime: 1000 * 60 * 5, // Cache for 5 minutes | ||
} ); | ||
}; | ||
|
||
export default useLocationViewsQuery; |