-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(tangle-dapp): Progress on
useTypedSearchParams
- Loading branch information
1 parent
4a19acc
commit e6fc994
Showing
2 changed files
with
39 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,34 +1,46 @@ | ||
'use client'; | ||
|
||
import { useSearchParams } from 'next/navigation'; | ||
import { useMemo } from 'react'; | ||
|
||
const useTypedSearchParams = <T extends object>(parsers: { | ||
[Key in keyof T]: (value: string) => T[Key] | undefined; | ||
}): Partial<T> => { | ||
const searchParams = useSearchParams(); | ||
|
||
const entries = Object.keys(parsers).map((stringKey) => { | ||
// TODO: Find a way to avoid casting here. | ||
const key = stringKey as keyof T; | ||
const parser = parsers[key]; | ||
const paramValue = searchParams.get(stringKey); | ||
const parsedValue = paramValue !== null ? parser(paramValue) : undefined; | ||
|
||
return [stringKey, parsedValue] as const; | ||
}); | ||
|
||
const result: Partial<T> = {}; | ||
|
||
for (const [stringKey, value] of entries) { | ||
// TODO: Find a way to avoid casting here. | ||
const key = stringKey as keyof T; | ||
|
||
if (value !== undefined) { | ||
result[key] = value; | ||
const entries = useMemo(() => { | ||
return Object.keys(parsers).map((stringKey) => { | ||
// TODO: Find a way to avoid casting here. | ||
const key = stringKey as keyof T; | ||
const parser = parsers[key]; | ||
const paramValue = searchParams.get(stringKey); | ||
let parsedValue: T[keyof T] | undefined; | ||
|
||
// Try parsing the value. If it fails, ignore the value. | ||
try { | ||
parsedValue = paramValue !== null ? parser(paramValue) : undefined; | ||
} catch { | ||
parsedValue = undefined; | ||
} | ||
|
||
return [stringKey, parsedValue] as const; | ||
}); | ||
}, [parsers, searchParams]); | ||
|
||
return useMemo(() => { | ||
const result: Partial<T> = {}; | ||
|
||
for (const [stringKey, value] of entries) { | ||
// TODO: Find a way to avoid casting here. | ||
const key = stringKey as keyof T; | ||
|
||
if (value !== undefined) { | ||
result[key] = value; | ||
} | ||
} | ||
} | ||
|
||
return result; | ||
return result; | ||
}, [entries]); | ||
}; | ||
|
||
export default useTypedSearchParams; |