Last active
November 13, 2022 13:53
-
-
Save valdemarua/c9f4085a0ae1896724973b10828fe3c4 to your computer and use it in GitHub Desktop.
React Hooks
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
// Dependencies: react-router, qs | |
// | |
// Usage: | |
// | |
// const [taskState, setTaskState] = useQueryState("state"); | |
// | |
// setTaskState("new") => /tasks?state=new | |
import { useCallback } from "react" | |
import { useHistory, useLocation } from "react-router-dom" | |
import qs from "qs" | |
export const useQueryState = query => { | |
const location = useLocation() | |
const history = useHistory() | |
const setQuery = useCallback( | |
value => { | |
const existingQueries = qs.parse(location.search, { | |
ignoreQueryPrefix: true, | |
}) | |
const queryString = qs.stringify( | |
{ ...existingQueries, [query]: value }, | |
{ skipNulls: true } | |
) | |
history.push(`${location.pathname}?${queryString}`) | |
}, | |
[history, location, query] | |
) | |
return [ | |
qs.parse(location.search, { ignoreQueryPrefix: true })[query], | |
setQuery, | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment