Skip to content

Instantly share code, notes, and snippets.

@valdemarua
Last active November 13, 2022 13:53
Show Gist options
  • Save valdemarua/c9f4085a0ae1896724973b10828fe3c4 to your computer and use it in GitHub Desktop.
Save valdemarua/c9f4085a0ae1896724973b10828fe3c4 to your computer and use it in GitHub Desktop.
React Hooks
// 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