Created
May 6, 2020 11:57
-
-
Save vesan/d50150681c89495cb2aa4ef431e4e674 to your computer and use it in GitHub Desktop.
Sync URL with state using react-router
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
// Usage: const [filters, setFilters] = useQuery(useState({})); | |
import { useHistory, useLocation } from "react-router-dom"; | |
export default function useQuery([defaultQuery, setValue], method = "push") { | |
const history = useHistory(); | |
const { search, pathname, hash } = useLocation(); | |
const hasParams = search.indexOf("=") > -1; | |
const setValueWithQuery = (newQuery) => { | |
setValue((state) => { | |
const fromUrl = Object.fromEntries(new URLSearchParams(search).entries()); | |
const updatedState = { ...state, ...fromUrl, ...newQuery }; | |
const searchFragment = new URLSearchParams(updatedState).toString(); | |
history[method](pathname + "?" + searchFragment + hash); | |
return updatedState; | |
}); | |
}; | |
return [ | |
hasParams | |
? { | |
...defaultQuery, | |
...Object.fromEntries(new URLSearchParams(search).entries()), | |
} | |
: { | |
...defaultQuery, | |
area: null, | |
supplier: null, | |
}, | |
setValueWithQuery, | |
]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment