Skip to content

Commit 1eaf9e2

Browse files
committed
reduce unnecessary rerender
1 parent ba8f699 commit 1eaf9e2

File tree

5 files changed

+27
-18
lines changed

5 files changed

+27
-18
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "react-api-fetching",
3-
"version": "0.5.1",
3+
"version": "0.5.2",
44
"description": "Make fetching API easier with React's hooks + context",
55
"source": "src/index.tsx",
66
"main": "dist/main.js",

src/__tests__/useApi.test.tsx

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,17 +48,15 @@ describe('useApi', () => {
4848

4949
rerender({ skip: false })
5050

51-
await waitFor(() => new Promise(r => setTimeout(r, 10)))
51+
await waitFor(() => expect(result.current.loading).toBeTruthy())
5252

53-
expect(result.current.called).toBeTruthy()
54-
expect(result.current.loading).toBeTruthy()
5553
expect(result.current.data).toBeUndefined()
54+
expect(result.current.called).toBeTruthy()
5655

57-
await waitFor(() => new Promise(r => setTimeout(r, 500)))
56+
await waitFor(() => expect(result.current.loading).toBeFalsy())
5857

59-
expect(fetch).toHaveBeenCalledTimes(1)
60-
expect(result.current.loading).toBeFalsy()
6158
expect(result.current.data).not.toBeUndefined()
59+
expect(fetch).toHaveBeenCalledTimes(1)
6260
})
6361

6462
it("automatically refetch if variables changed", async () => {

src/cache.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@ export class Cache {
1616
data: Record<string, ApiResult> = {}
1717
subscriptions: Record<string, (() => void)[]> = {}
1818

19+
initialize = <TData, TError>(key: string, value: ApiResult<TData, TError>) => {
20+
if (!this.data[key]) {
21+
this.data[key] = value
22+
}
23+
}
24+
1925
get = <TData, TError>(key: string) => {
2026
return (this.data[key] || defaultResult) as ApiResult<TData, TError>
2127
}

src/hooks.tsx

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@ export function useRerender() {
2525
return rerender
2626
}
2727

28+
export function useInitialize(initialize: () => void) {
29+
useMemo(initialize, [])
30+
}
31+
2832
export const useEnhancedEffect = canUseDOM ? useLayoutEffect : useEffect
2933

3034
export function useCachedData(key: string, cache: Cache){

src/index.tsx

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import { createContext, useCallback, useContext, useEffect, useMemo, useReducer, useRef } from 'react'
22
import { deepEqual, deepMerge, generateConcurrentFn } from './utils'
3-
import { useValueRef, useEnhancedMemo, useCachedData, useEnhancedEffect } from './hooks'
4-
import { ApiResult, Cache, defaultResult, generateCacheKey, isCached } from './cache'
3+
import { useValueRef, useEnhancedMemo, useCachedData, useEnhancedEffect, useInitialize } from './hooks'
4+
import { Cache, defaultResult, generateCacheKey, isCached } from './cache'
5+
import type { ApiResult } from './cache'
6+
57
export { Cache } from './cache'
68

79
export type ApiVariables<T extends Partial<Record<'body' | 'query' | 'body', any>> = {}> = T
@@ -347,21 +349,21 @@ function createUseApi<
347349
const cached = useMemo(() => isCached(cacheKey, cache), [cacheKey, cache])
348350

349351
const calledRef = useRef(!skip || cached)
350-
const loadingRef = useRef(!skip && !cached)
352+
353+
// set loading: true in first render
354+
useInitialize(() => {
355+
if (skip || cached) return
356+
cache.initialize(cacheKey, { ...defaultResult, loading: true })
357+
})
351358

352359
const onFetch = useCallback(async () => {
353360
calledRef.current = true
354-
loadingRef.current = true
355361
if (optsRef.current.onFetch) await optsRef.current.onFetch()
356362
}, [])
357-
const onCompleted = useCallback(async (params: OnCompletedParams<T, TData, TError, TVariables, K>) => {
358-
loadingRef.current = false
359-
if (optsRef.current.onCompleted) await optsRef.current.onCompleted(params)
360-
}, [])
363+
361364
const [fetch, result] = useLazyApi<K, TApiData, TApiError, TApiVariables>(key, {
362365
...lazyOpts,
363-
onFetch,
364-
onCompleted
366+
onFetch
365367
})
366368

367369
useEffect(() => {
@@ -372,7 +374,6 @@ function createUseApi<
372374

373375
return {
374376
...result,
375-
loading: result.loading || loadingRef.current,
376377
called: calledRef.current
377378
}
378379
}

0 commit comments

Comments
 (0)