Skip to content

Commit

Permalink
refactor(use-url-hash-state): update impl
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed Oct 30, 2023
1 parent 2d9ae53 commit 0dbbdc6
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions src/use-url-hash-state/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,16 @@ const subscribe: Parameters<typeof useSyncExternalStore>[0] = (() => {
// eslint-disable-next-line @typescript-eslint/ban-types -- workaround TypeScript bug
const isFunction = (x: unknown): x is Function => typeof x === 'function';

function useUrlHashState<T extends string | number>(
function useUrlHashState<T>(
key: string,
defaultValue?: undefined
): readonly [T | undefined, React.Dispatch<React.SetStateAction<T | undefined>>];
function useUrlHashState<T extends string | number>(
function useUrlHashState<T>(
key: string,
defaultValue: T,
transform?: (value: string) => T
): readonly [T, React.Dispatch<React.SetStateAction<T>>];
function useUrlHashState<T extends string | number>(
function useUrlHashState<T>(
key: string,
defaultValue?: T | undefined,
transform: (value: string) => T = identity
Expand All @@ -66,10 +66,10 @@ function useUrlHashState<T extends string | number>(
() => defaultValue
),
useCallback((updater) => {
const searchParams = new URLSearchParams(location.hash.slice(1));

const currentHash = location.hash;

const searchParams = new URLSearchParams(currentHash.slice(1));

let newValue;

if (isFunction(updater)) {
Expand All @@ -80,7 +80,7 @@ function useUrlHashState<T extends string | number>(
}

if (
(defaultValue !== undefined && newValue === defaultValue)
newValue === defaultValue
|| newValue === undefined
) {
searchParams.delete(key);
Expand All @@ -94,7 +94,7 @@ function useUrlHashState<T extends string | number>(
return;
}

location.hash = searchParams.toString();
location.hash = newHash;
}, [defaultValue, key, memoized_transform])
] as const;
}
Expand Down

0 comments on commit 0dbbdc6

Please sign in to comment.