Skip to content

Commit

Permalink
refactor: create utils file for housing utility fuctions
Browse files Browse the repository at this point in the history
  • Loading branch information
Ala committed Jun 15, 2024
1 parent 897d06d commit 727178d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 20 deletions.
21 changes: 1 addition & 20 deletions src/hooks/use-fetch.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// This hook does not deal with caching, de-bouncing or de-duping
// I would seriously consider using TanStack Query instead of this hook
import { deepEqual } from '../utils'
import { useCallback, useEffect, useRef, useState } from 'react'

type UseFetchResponse<T> = {
Expand All @@ -15,26 +16,6 @@ type UseFetch = {
<T>(url: string, trigger: boolean, requestOptions: RequestInit): UseFetchResponse<T>
}

const deepEqual = (a: unknown, b: unknown): boolean => {
if (a === b) {
return true
}
if (!(a instanceof Object) || !(b instanceof Object)) {
return false
}
if (a.constructor !== b.constructor) {
return false
}
const aKeys = Object.keys(a)
const bKeys = Object.keys(b)

if (aKeys.length !== bKeys.length || aKeys.some(key => !bKeys.includes(key))) {
return false
}

return aKeys.every(key => deepEqual(a[key as keyof typeof a], b[key as keyof typeof b]))
}

export const useFetch: UseFetch = <T = unknown>(
url: string,
trigger?: boolean | RequestInit,
Expand Down
19 changes: 19 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export const deepEqual = (a: unknown, b: unknown): boolean => {
if (a === b) {
return true
}
if (!(a instanceof Object) || !(b instanceof Object)) {
return false
}
if (a.constructor !== b.constructor) {
return false
}
const aKeys = Object.keys(a)
const bKeys = Object.keys(b)

if (aKeys.length !== bKeys.length || aKeys.some(key => !bKeys.includes(key))) {
return false
}

return aKeys.every(key => deepEqual(a[key as keyof typeof a], b[key as keyof typeof b]))
}

0 comments on commit 727178d

Please sign in to comment.