Skip to content

Commit

Permalink
Merge pull request #127 from danybeltran/feat-useresponsetime
Browse files Browse the repository at this point in the history
feat(responseTime):
  • Loading branch information
danybeltran authored Jan 19, 2023
2 parents e79678c + 927bae4 commit f778549
Show file tree
Hide file tree
Showing 7 changed files with 45 additions and 11 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "http-react",
"version": "2.5.8",
"version": "2.5.9",
"description": "React hooks for data fetching",
"main": "dist/index.js",
"scripts": {
Expand Down
1 change: 1 addition & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export {
useFetchId as useFetchId,
useFetchBlob as useBlob,
useFetchText as useText,
useFetchResponseTime as useResponseTime,
useGET,
useDELETE,
useHEAD,
Expand Down
7 changes: 7 additions & 0 deletions src/hooks/others.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
hasErrors,
isPending,
lastResponses,
requestResponseTimes,
requestsProvider,
runningRequests,
useHRFContext
Expand Down Expand Up @@ -417,6 +418,12 @@ export function useFetchText<FetchDataType = string, BodyType = any>(
})
}

export function useFetchResponseTime(id: any) {
return useFetch({
id
}).responseTime
}

/**
* Make a graphQL request
*/
Expand Down
23 changes: 18 additions & 5 deletions src/hooks/use-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ import {
valuesMemory,
willSuspend,
canDebounce,
resolvedOnErrorCalls
resolvedOnErrorCalls,
requestInitialTimes,
requestResponseTimes
} from '../internal'

import { DEFAULT_RESOLVER, METHODS } from '../internal/constants'
Expand All @@ -38,6 +40,7 @@ import {
import {
createImperativeFetch,
createRequestFn,
getTimePassed,
hasBaseUrl,
isDefined,
isFunction,
Expand Down Expand Up @@ -420,7 +423,10 @@ export function useFetch<FetchDataType = any, BodyType = any>(
try {
const json = await fetch(realUrl + c.query, {
...ctx,
signal: newAbortController.signal,
signal: (() => {
requestInitialTimes[resolvedKey] = Date.now()
return newAbortController.signal
})(),
...optionsConfig,
body: isFunction(formatBody)
? // @ts-ignore // If formatBody is a function
Expand All @@ -433,6 +439,7 @@ export function useFetch<FetchDataType = any, BodyType = any>(
...c.headers
} as Headers
})
requestResponseTimes[resolvedKey] = getTimePassed(resolvedKey)

lastResponses[resolvedKey] = json

Expand Down Expand Up @@ -597,7 +604,9 @@ export function useFetch<FetchDataType = any, BodyType = any>(
}
} finally {
setLoading(false)
canDebounce[resolvedKey] = true
queue(() => {
canDebounce[resolvedKey] = true
}, debounce)
runningRequests[resolvedKey] = false
requestsProvider.emit(resolvedKey, {
requestCallId,
Expand Down Expand Up @@ -1065,7 +1074,9 @@ export function useFetch<FetchDataType = any, BodyType = any>(
)

if (!suspense) {
suspenseInitialized[resolvedKey] = true
if (url !== '') {
suspenseInitialized[resolvedKey] = true
}
}

React.useMemo(() => {
Expand Down Expand Up @@ -1293,7 +1304,8 @@ export function useFetch<FetchDataType = any, BodyType = any>(
/**
* The request key
*/
key: resolvedKey
key: resolvedKey,
responseTime: requestResponseTimes[resolvedKey]
} as unknown as {
data: FetchDataType
loading: boolean
Expand All @@ -1315,6 +1327,7 @@ export function useFetch<FetchDataType = any, BodyType = any>(
response: CustomResponse<FetchDataType>
id: any
key: string
responseTime: number
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ export {
useUNLINK,
useGql,
useImperative,
useResolve
useResolve,
useResponseTime
} from './hooks'

export { FetchConfig, SSRSuspense } from './components'
Expand Down
4 changes: 4 additions & 0 deletions src/internal/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ export const abortControllers: any = {}

export const canDebounce: any = {}

export const requestInitialTimes: any = {}

export const requestResponseTimes: any = {}

/**
* Request with errors
*/
Expand Down
16 changes: 12 additions & 4 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
cacheForMutation,
defaultCache,
previousConfig,
requestInitialTimes,
requestsProvider,
runningMutate,
valuesMemory
Expand Down Expand Up @@ -80,7 +81,7 @@ export function setURLParams(str: string = '', $params: any = {}) {
return (
str
.split('/')
.map($segment => {
.map(($segment) => {
const [segment] = $segment.split('?')
if (segment.startsWith('[') && segment.endsWith(']')) {
const paramName = segment.replace(/\[|\]/g, '')
Expand Down Expand Up @@ -109,6 +110,13 @@ export function setURLParams(str: string = '', $params: any = {}) {
)
}

export function getTimePassed(key: any) {
return (
Date.now() -
(isDefined(requestInitialTimes[key]) ? requestInitialTimes[key] : 0)
)
}

/**
* Creates a new request function. This is for usage with fetcher and fetcher.extend
*/
Expand All @@ -133,7 +141,7 @@ export function createRequestFn(
const rawUrl = setURLParams(url, params)

const reqQueryString = Object.keys(query)
.map(q => [q, query[q]].join('='))
.map((q) => [q, query[q]].join('='))
.join('&')

const reqConfig = {
Expand Down Expand Up @@ -231,7 +239,7 @@ export const createImperativeFetch = (ctx: FetchContextType) => {

return Object.fromEntries(
new Map(
keys.map(k => [
keys.map((k) => [
k.toLowerCase(),
(url, config = {}) =>
(useFetch as any)[k.toLowerCase()](
Expand All @@ -251,7 +259,7 @@ export const createImperativeFetch = (ctx: FetchContextType) => {
*/
export function revalidate(id: any | any[]) {
if (Array.isArray(id)) {
id.map(reqId => {
id.map((reqId) => {
if (isDefined(reqId)) {
const key = serialize(reqId)

Expand Down

0 comments on commit f778549

Please sign in to comment.