Skip to content

Commit

Permalink
refactor more, cleaner more contained solution
Browse files Browse the repository at this point in the history
  • Loading branch information
Flirre committed Feb 27, 2024
1 parent 80c21f9 commit ec84c87
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions src/atomWithHash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,7 @@ export function atomWithHash<Value>(
},
): WritableAtom<Value, [SetStateActionWithReset<Value>], void> {
const serialize = options?.serialize || JSON.stringify;
let initialValueInHash: string | null = null;
if (typeof window !== 'undefined') {
initialValueInHash = new URLSearchParams(window.location.hash.slice(1)).get(
key,
);
}

const deserialize = options?.deserialize || safeJSONParse(initialValue);
const subscribe =
options?.subscribe ||
Expand All @@ -57,15 +52,20 @@ export function atomWithHash<Value>(
if (typeof setHashOption === 'function') {
setHash = setHashOption;
}
const strAtom = atom(initialValueInHash);
const isLocationAvailable =
typeof window !== 'undefined' && !!window.location;

const strAtom = atom(
isLocationAvailable
? new URLSearchParams(window.location.hash.slice(1)).get(key)
: null,
);
strAtom.onMount = (setAtom) => {
if (typeof window === 'undefined' || !window.location) {
if (!isLocationAvailable) {
return undefined;
}
const callback = () => {
const searchParams = new URLSearchParams(window.location.hash.slice(1));
const str = searchParams.get(key);
setAtom(str);
setAtom(new URLSearchParams(window.location.hash.slice(1)).get(key));
};
const unsubscribe = subscribe(callback);
callback();
Expand Down

0 comments on commit ec84c87

Please sign in to comment.