Skip to content

Commit 467914d

Browse files
committed
fix(re-render, onPropsChange):
- Fixes unnecesart initial re-render - Removed the 'onPropsChange' api
1 parent 8e03e03 commit 467914d

File tree

3 files changed

+54
-135
lines changed

3 files changed

+54
-135
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": "http-react",
3-
"version": "2.9.6",
3+
"version": "2.9.7",
44
"description": "React hooks for data fetching",
55
"main": "dist/index.js",
66
"scripts": {

src/hooks/use-fetch.ts

Lines changed: 53 additions & 112 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,6 @@ export function useFetch<FetchDataType = any, BodyType = any>(
101101
onOnline = ctx.onOnline,
102102
onOffline = ctx.onOffline,
103103
onMutate,
104-
onPropsChange,
105104
revalidateOnMount = ctx.revalidateOnMount,
106105
url = '',
107106
query = {},
@@ -153,7 +152,6 @@ export function useFetch<FetchDataType = any, BodyType = any>(
153152

154153
const willResolve = isDefined(onResolve)
155154
const handleError = isDefined(onError)
156-
const handlePropsChange = isDefined(onPropsChange)
157155
const handleOnAbort = isDefined(onAbort)
158156
const handleMutate = isDefined(onMutate)
159157
const handleOnline = isDefined(onOnline)
@@ -334,6 +332,17 @@ export function useFetch<FetchDataType = any, BodyType = any>(
334332

335333
const { data, loading, online, error, completedAttempts } = fetchState
336334

335+
const isLoading = isExpired ? isPending(resolvedKey) || loading : false
336+
337+
const loadingFirst =
338+
!(hasData[resolvedDataKey] || hasData[resolvedKey]) && isLoading
339+
340+
if (!isExpired) {
341+
if (error) {
342+
setError(null)
343+
}
344+
}
345+
337346
function setData(v: any) {
338347
setFetchState(p => {
339348
if (isFunction(v)) {
@@ -493,15 +502,8 @@ export function useFetch<FetchDataType = any, BodyType = any>(
493502

494503
cacheProvider.set(ageKey, Date.now() - 1)
495504

496-
// @ts-ignore null is a falsy value
497-
setFetchState(prev => ({
498-
...prev,
499-
loading: true,
500-
error: null
501-
}))
502-
503505
requestsProvider.emit(resolvedKey, {
504-
requestCallId,
506+
requestCallId: loadingFirst ? requestCallId : undefined,
505507
loading: true,
506508
requestAbortController: newAbortController,
507509
error: null
@@ -535,6 +537,7 @@ export function useFetch<FetchDataType = any, BodyType = any>(
535537

536538
const r = isRequest
537539
? new Request(realUrl + c.query, {
540+
...ctx,
538541
...reqConfig,
539542
...optionsConfig,
540543
signal: (() => {
@@ -544,16 +547,16 @@ export function useFetch<FetchDataType = any, BodyType = any>(
544547
'Content-Type': 'application/json',
545548
...ctx.headers,
546549
..._headers,
547-
...optionsConfig.headers,
550+
...config.headers,
548551
...c.headers
549552
}
550553
} as any)
551554
: new Request(realUrl + c.query, {
552555
...ctx,
556+
...optionsConfig,
553557
signal: (() => {
554558
return newAbortController.signal
555559
})(),
556-
...optionsConfig,
557560
body: isFunction(formatBody)
558561
? // @ts-ignore // If formatBody is a function
559562
formatBody(optionsConfig?.body as any)
@@ -563,7 +566,7 @@ export function useFetch<FetchDataType = any, BodyType = any>(
563566
...ctx.headers,
564567
...config.headers,
565568
...c.headers
566-
} as Headers
569+
}
567570
})
568571
if (logStart) {
569572
;(onFetchStart as any)(r, optionsConfig, ctx)
@@ -813,7 +816,7 @@ export function useFetch<FetchDataType = any, BodyType = any>(
813816
...p,
814817
data: $$data ?? p.data,
815818
error: isDefined($$error) ? $$error : p.error,
816-
loading: false ?? p.loading,
819+
loading: false,
817820
completedAttempts: $$completedAttempts ?? p.completedAttempts
818821
}))
819822

@@ -828,6 +831,7 @@ export function useFetch<FetchDataType = any, BodyType = any>(
828831
...rpc
829832
})
830833

834+
willSuspend[resolvedKey] = false
831835
queue(() => {
832836
canDebounce[resolvedKey] = true
833837
}, debounce)
@@ -917,18 +921,24 @@ export function useFetch<FetchDataType = any, BodyType = any>(
917921
}
918922

919923
if (v.requestCallId !== requestCallId) {
920-
queue(() => {
921-
setFetchState(p => {
922-
return {
923-
...p,
924-
completedAttempts: completedAttempts ?? p.completedAttempts,
925-
loading: loading ?? p.loading,
926-
data: !jsonCompare($data, p.data) ? $data : p.data ?? p.data,
927-
error: $error,
928-
online: online ?? p.online
929-
}
924+
if (!willSuspend[resolvedKey]) {
925+
queue(() => {
926+
setFetchState(p => {
927+
const n = {
928+
...p,
929+
completedAttempts: completedAttempts ?? p.completedAttempts,
930+
loading: loading ?? p.loading,
931+
data: !jsonCompare($data, p.data) ? $data : p.data ?? p.data,
932+
error: $error,
933+
online: online ?? p.online
934+
}
935+
936+
if (jsonCompare(n, p)) return p
937+
938+
return n
939+
})
930940
})
931-
})
941+
}
932942
}
933943
}
934944

@@ -937,7 +947,12 @@ export function useFetch<FetchDataType = any, BodyType = any>(
937947
return () => {
938948
requestsProvider.removeListener(resolvedKey, waitFormUpdates)
939949
}
940-
}, [JSON.stringify(optionsConfig), requestCallId])
950+
}, [
951+
JSON.stringify(optionsConfig),
952+
resolvedKey,
953+
resolvedDataKey,
954+
requestCallId
955+
])
941956

942957
const reValidate = React.useCallback(
943958
async function reValidate() {
@@ -1182,19 +1197,21 @@ export function useFetch<FetchDataType = any, BodyType = any>(
11821197
}
11831198
}
11841199

1185-
useEffect(() => {
1186-
if (windowExists) {
1187-
if (canRevalidate && url !== '') {
1188-
if (!jsonCompare(previousConfig[resolvedKey], optionsConfig)) {
1189-
if (!isPending(resolvedKey)) {
1190-
initializeRevalidation()
1191-
} else {
1192-
setLoading(true)
1200+
React.useMemo(() => {
1201+
if (!runningRequests[resolvedKey] && isExpired) {
1202+
if (windowExists) {
1203+
if (canRevalidate && url !== '') {
1204+
if (!jsonCompare(previousConfig[resolvedKey], optionsConfig)) {
1205+
if (!isPending(resolvedKey)) {
1206+
initializeRevalidation()
1207+
} else {
1208+
setLoading(true)
1209+
}
11931210
}
11941211
}
11951212
}
11961213
}
1197-
}, [resolvedKey, serialize(optionsConfig)])
1214+
}, [resolvedKey, serialize(optionsConfig), canRevalidate])
11981215

11991216
useEffect(() => {
12001217
const revalidateAfterUnmount = revalidateOnMount
@@ -1312,75 +1329,6 @@ export function useFetch<FetchDataType = any, BodyType = any>(
13121329
}
13131330
}
13141331

1315-
useEffect(() => {
1316-
const rev = {
1317-
revalidate: () => queue(() => revalidate(id)),
1318-
cancel: () => {
1319-
try {
1320-
if (url !== '') {
1321-
if (previousConfig[resolvedKey] !== serialize(optionsConfig)) {
1322-
if (auto) {
1323-
setLoading(() => {
1324-
requestAbortController?.abort()
1325-
queue(() => {
1326-
initializeRevalidation()
1327-
})
1328-
return true
1329-
})
1330-
}
1331-
}
1332-
}
1333-
} catch (err) {}
1334-
},
1335-
fetcher: imperativeFetch,
1336-
props: optionsConfig,
1337-
previousProps: previousProps[resolvedKey]
1338-
}
1339-
1340-
queue(() => {
1341-
if (!canRevalidate && url !== '' && debounce) {
1342-
canDebounce[resolvedKey] = true
1343-
}
1344-
})
1345-
1346-
if (serialize(previousProps[resolvedKey]) !== serialize(optionsConfig)) {
1347-
if (debounce) {
1348-
canDebounce[resolvedKey] = true
1349-
}
1350-
if (handlePropsChange) {
1351-
;(onPropsChange as any)(rev as any)
1352-
}
1353-
if (url !== '') {
1354-
previousProps[resolvedKey] = optionsConfig
1355-
}
1356-
if (cancelOnChange) {
1357-
if (url !== '') {
1358-
if (auto) {
1359-
setLoading(() => {
1360-
requestAbortController?.abort()
1361-
queue(() => {
1362-
initializeRevalidation()
1363-
})
1364-
return true
1365-
})
1366-
}
1367-
}
1368-
}
1369-
if (canRevalidate && url !== '') {
1370-
const debounceTimeout = setTimeout(() => {
1371-
initializeRevalidation()
1372-
if (suspenseInitialized[resolvedKey]) {
1373-
}
1374-
}, debounce)
1375-
1376-
return () => {
1377-
clearTimeout(debounceTimeout)
1378-
}
1379-
}
1380-
}
1381-
return () => {}
1382-
}, [serialize(optionsConfig)])
1383-
13841332
const [$requestStart, $requestEnd] = [
13851333
notNull(cacheProvider.get('requestStart' + resolvedDataKey))
13861334
? new Date(cacheProvider.get('requestStart' + resolvedDataKey))
@@ -1400,20 +1348,13 @@ export function useFetch<FetchDataType = any, BodyType = any>(
14001348
? new Date(cacheProvider.get('expiration' + resolvedDataKey))
14011349
: null
14021350

1403-
const isLoading = isExpired ? isPending(resolvedKey) || loading : false
1404-
1405-
const isFailed =
1406-
(hasErrors[resolvedDataKey] || hasErrors[resolvedKey] || error) &&
1407-
!isLoading
1351+
const isFailed = (hasErrors[resolvedDataKey] || error) && !isLoading
14081352

14091353
const responseData =
14101354
(error && isFailed ? (cacheIfError ? thisCache : null) : thisCache) ?? def
14111355

14121356
const isSuccess = !isLoading && !isFailed
14131357

1414-
const loadingFirst =
1415-
!(hasData[resolvedDataKey] || hasData[resolvedKey]) && isLoading
1416-
14171358
const oneRequestResolved =
14181359
!loadingFirst &&
14191360
(hasData[resolvedDataKey] ||

src/types/index.ts

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -191,19 +191,6 @@ export type FetchConfigType<FetchDataType = any, BodyType = any> = Omit<
191191
*/
192192
fetcher: ImperativeFetch
193193
) => void
194-
/**
195-
* Function to run when props change
196-
*/
197-
onPropsChange?: (rev: {
198-
revalidate: () => void
199-
cancel: {
200-
(reason?: any): void
201-
(): void
202-
}
203-
fetcher: ImperativeFetch
204-
props: FetchConfigTypeNoUrl<FetchDataType, BodyType>
205-
previousProps: FetchConfigTypeNoUrl<FetchDataType, BodyType>
206-
}) => void
207194
/**
208195
* Function to run when the request fails
209196
*/
@@ -308,19 +295,10 @@ export type FetchConfigType<FetchDataType = any, BodyType = any> = Omit<
308295
* @default true
309296
*/
310297
cacheIfError?: boolean
311-
/**
312-
* If `true`, the request will be overwriten with other configurations passed to `useFetch` (such as method, query, params, body, etc)
313-
* @default true
314-
*/
315-
overwrite?: boolean
316298
/**
317299
* The max age a page should be cached (with no request)
318300
*/
319301
maxCacheAge?: TimeSpan
320-
/**
321-
* Similar to `resolver` but takes the data coming from resolver instead of the actual response
322-
*/
323-
middleware?: <R = FetchDataType>(data: R) => FetchDataType
324302
}
325303

326304
// If first argument is a string

0 commit comments

Comments
 (0)