Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(atomWithHash): initial value from hash #31

Merged
merged 4 commits into from
Feb 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion __tests__/atomWithHash_spec.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { StrictMode, useMemo } from 'react';
import React, { StrictMode, useEffect, useMemo, useState } from 'react';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useAtom } from 'jotai/react';
Expand Down Expand Up @@ -186,6 +186,37 @@ describe('atomWithHash', () => {
await user.type(screen.getByLabelText('b'), '1');
await waitFor(() => expect(paramBMockFn).toBeCalledTimes(4));
});

it('sets initial value from hash', async () => {
window.location.hash = '#count=2';
const countAtom = atomWithHash('count', 0);

const Counter = () => {
const [count] = useAtom(countAtom);
const [countWasZero, setCountWasZero] = useState(false);

useEffect(() => {
if (count === 0) {
setCountWasZero(true);
}
}, [count]);
return (
<>
<div>count: {count}</div>
<div>count was zero: {countWasZero.toString()}</div>
</>
);
};

const { findByText } = render(
<StrictMode>
<Counter />
</StrictMode>,
);

await findByText('count: 2');
await findByText('count was zero: false');
});
});

describe('atomWithHash without window', () => {
Expand Down
16 changes: 11 additions & 5 deletions src/atomWithHash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export function atomWithHash<Value>(
},
): WritableAtom<Value, [SetStateActionWithReset<Value>], void> {
const serialize = options?.serialize || JSON.stringify;

const deserialize = options?.deserialize || safeJSONParse(initialValue);
const subscribe =
options?.subscribe ||
Expand All @@ -51,15 +52,20 @@ export function atomWithHash<Value>(
if (typeof setHashOption === 'function') {
setHash = setHashOption;
}
const strAtom = atom<string | null>(null);
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
Loading