Skip to content

Commit cc13f57

Browse files
committed
fix infinite re-renders
1 parent 374f7da commit cc13f57

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

src/apps/talent-search/src/lib/services/use-fetch-talent-matches.ts

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { uniqBy } from 'lodash'
2-
import { useEffect, useState } from 'react'
2+
import { useCallback, useEffect, useMemo, useState } from 'react'
33
import useSWR, { SWRResponse } from 'swr'
44

55
import { EnvironmentConfig } from '~/config'
@@ -37,14 +37,14 @@ export function useFetchTalentMatches(
3737
revalidateOnFocus: false,
3838
})
3939

40-
const matches = data?.data
40+
const matches = useMemo(() => data?.data ?? [], [data])
4141

4242
return {
4343
error: !!error,
44-
loading: !matches,
44+
loading: !data?.data,
4545
matches: matches ?? [],
4646
page: data?.page ?? 0,
47-
ready: !!matches,
47+
ready: !!data?.data,
4848
total: data?.total ?? 0,
4949
totalPages: data?.totalPages ?? 0,
5050
}
@@ -67,10 +67,16 @@ export function useInfiniteTalentMatches(
6767
const [page, setPage] = useState(1)
6868
const matchResponse = useFetchTalentMatches(skills, page, pageSize)
6969

70-
function fetchNext(): void {
70+
const fetchNext = useCallback(() => {
7171
setPage(p => p + 1)
72-
}
72+
}, [])
73+
74+
// clear matches when skills array is updated
75+
useEffect(() => {
76+
setMatches([])
77+
}, [skills])
7378

79+
// when we have new matches, concatenate the response to the matches array
7480
useEffect(() => {
7581
setMatches(m => uniqBy([...m, ...matchResponse.matches], 'userId'))
7682
}, [matchResponse.matches])

0 commit comments

Comments
 (0)