Skip to content

Commit 3492aad

Browse files
Affiliate Stats and Referral Hooks
1 parent c2ea7ef commit 3492aad

File tree

2 files changed

+54
-16
lines changed

2 files changed

+54
-16
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { useInfiniteQuery } from '@tanstack/react-query'
2+
import { useSupabase } from 'app/utils/supabase/useSupabase'
3+
import { throwIf } from 'app/utils/throwIf'
4+
5+
/**
6+
/**
7+
* Infinite query to fetch referrals
8+
* @param pageSize - number of items to fetch per page
9+
*/
10+
export function useAffiliateReferrals({ pageSize = 10 }: { pageSize?: number } = {}) {
11+
const supabase = useSupabase()
12+
async function fetchAffiliateReferrals({ pageParam }: { pageParam: number }) {
13+
const from = pageParam * pageSize
14+
const to = (pageParam + 1) * pageSize - 1
15+
const request = supabase.from('affiliate_referrals').select('*').range(from, to)
16+
const { data, error } = await request
17+
throwIf(error)
18+
return data
19+
}
20+
return useInfiniteQuery({
21+
queryKey: ['affiliate_referrals'],
22+
initialPageParam: 0,
23+
getNextPageParam: (lastPage, _allPages, lastPageParam) => {
24+
if (lastPage !== null && lastPage.length < pageSize) return undefined
25+
return lastPageParam + 1
26+
},
27+
getPreviousPageParam: (_firstPage, _allPages, firstPageParam) => {
28+
if (firstPageParam <= 1) {
29+
return undefined
30+
}
31+
return firstPageParam - 1
32+
},
33+
queryFn: fetchAffiliateReferrals,
34+
})
35+
}
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,25 @@
1-
import type { Tables } from '@my/supabase/database-generated.types'
2-
import type { PostgrestError } from '@supabase/postgrest-js'
3-
import { useQuery, type UseQueryResult } from '@tanstack/react-query'
1+
import { useQuery } from '@tanstack/react-query'
42
import { useSupabase } from 'app/utils/supabase/useSupabase'
53

6-
export const useAffiliateStats = (): UseQueryResult<Tables<'affiliate_stats'>, PostgrestError> => {
4+
export function useAffiliateStats() {
75
const supabase = useSupabase()
8-
return useQuery({
9-
queryKey: ['affiliate_stats'],
10-
queryFn: async () => {
11-
const { data, error } = await supabase.from('affiliate_stats').select('*').single()
12-
if (error) {
13-
// no rows in receipts table
14-
if (error.code === 'PGRST116') {
15-
return null
16-
}
17-
throw new Error(error.message)
6+
async function fetchAffiliateStats() {
7+
const request = supabase.from('affiliate_stats_summary').select('*').single()
8+
9+
const { data, error } = await request
10+
if (error) {
11+
// no rows in receipts table
12+
if (error.code === 'PGRST116') {
13+
return null
1814
}
19-
return data
20-
},
15+
throw new Error(error.message)
16+
}
17+
18+
return data
19+
}
20+
21+
return useQuery({
22+
queryKey: ['affiliate_stats_summary'],
23+
queryFn: fetchAffiliateStats,
2124
})
2225
}

0 commit comments

Comments
 (0)