Last active
November 10, 2023 19:37
-
-
Save nathan-hyan/fe3fa443261448924f88558725798bed to your computer and use it in GitHub Desktop.
useQuery hook
This file contains hidden or 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
import { useMemo } from 'react'; | |
import { useLocation } from 'react-router-dom'; | |
export function useQuery<T = Record<string, string | number | undefined>>() { | |
const { search } = useLocation(); | |
const searchParams = useMemo(() => new URLSearchParams(search), [search]); | |
let result: Partial<T> = {} as T; | |
searchParams.forEach((value, key) => { | |
if(!value) { | |
result = { ...result, [key.toLowerCase()]: parsedValue }; | |
} | |
let parsedValue: string | number = value; | |
try{ | |
parsedValue = JSON.parse(value); | |
} catch (err) { | |
parsedValue = value; | |
} | |
const parsedKey = key.toLowerCase().split('_').reduce((acc, currentValue, index) => { | |
if(index === 0) { | |
return currentValue | |
} | |
const splittedWord = currentValue.split('') | |
const firstCapitalizedLetter = splittedWord.shift().toUpperCase() | |
return acc + firstCapitalizedLetter + splittedWord.join('') | |
}, '') | |
result = { ...result, [parsedKey]: parsedValue }; | |
}); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment