Skip to content

Instantly share code, notes, and snippets.

@trebor
Created June 30, 2020 14:48
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 trebor/9a19b889c8b1e3fd77d1e2b542f05dee to your computer and use it in GitHub Desktop.
Save trebor/9a19b889c8b1e3fd77d1e2b542f05dee to your computer and use it in GitHub Desktop.
import { atom, selector } from "recoil";
export const getUrlParam = (name, defaultValue, setIfUnset = false) => {
const setValue = new URL(window.location).searchParams.get(name);
if (setIfUnset && !setValue) setUrlParam(name, defaultValue);
return setValue || defaultValue;
};
export const setUrlParam = (name, value, title = document.title) => {
const { protocol, host, pathname } = window.location;
const searchParams = new URL(window.location).searchParams;
searchParams.set(name, value);
const url = `${protocol}//${host}${pathname}?${searchParams}`;
window.history.pushState({ path: url }, title, url);
};
export const clearUrlParam = name => {
const { protocol, host, pathname } = window.location;
const searchParams = new URL(window.location).searchParams;
searchParams.delete(name);
const paramsString = searchParams.toString();
const url = `${protocol}//${host}${pathname}${
paramsString.length > 0 ? "?" : ""
}${paramsString}`;
window.history.pushState({ path: url }, "", url);
};
// a general purpose url param recoil atom
export const urlParamAtom = ({ name, default: _default }) => {
const state = atom({
key: `${name}-url-param-atom`,
default: getUrlParam(name) || _default,
});
return selector({
key: `${name}-url-param-selector`,
get: ({ get }) => get(state),
set: ({ set }, value) => {
setUrlParam(name, value);
set(state, value);
},
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment