Skip to content

Instantly share code, notes, and snippets.

@vesan
Created May 6, 2020 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vesan/d50150681c89495cb2aa4ef431e4e674 to your computer and use it in GitHub Desktop.
Save vesan/d50150681c89495cb2aa4ef431e4e674 to your computer and use it in GitHub Desktop.
Sync URL with state using react-router
// 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