Skip to content
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,5 @@ results
.env

.claude/settings.json

next-env.d.ts
7 changes: 0 additions & 7 deletions packages/example-nextjs16/next-env.d.ts

This file was deleted.

3 changes: 0 additions & 3 deletions packages/urlstate/useInsertionEffect.ts

This file was deleted.

5 changes: 5 additions & 0 deletions packages/urlstate/useIsomorphicLayoutEffect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import React from 'react';

// subscribe before paint; useLayoutEffect warns on the server
export const useIsomorphicLayoutEffect =
typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect;
49 changes: 49 additions & 0 deletions packages/urlstate/useSharedState/useSharedState.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import React from 'react';
import { act, renderHook } from '@testing-library/react';

import { useSharedState } from './useSharedState';
Expand Down Expand Up @@ -200,6 +201,54 @@ describe('useSharedState', () => {
expect(mockSubscriber).toHaveBeenCalledTimes(1);
});

test('should catch a store write that lands between render and subscribe', () => {
const defaultState = { count: 0 };
const updated = { count: 7 };
// renders after the hook, so the write lands before it subscribes
const WriteMidRender = () => {
subscribers.stateMap.set(defaultState, updated);
return null;
};

const { result } = renderHook(() => useSharedState(defaultState), {
wrapper: ({ children }) =>
React.createElement(
React.Fragment,
null,
children,
React.createElement(WriteMidRender),
),
});

expect(result.current.state).toStrictEqual(updated);
});

test('should subscribe before paint, not after', () => {
const defaultState = { count: 0 };
const order: string[] = [];
vi.spyOn(subscribers.subscribers, 'add').mockImplementation(() => {
order.push('subscribe');
return () => void 0;
});
const Probe = () => {
React.useLayoutEffect(() => void order.push('layout'), []);
React.useEffect(() => void order.push('effect'), []);
return null;
};

renderHook(() => useSharedState(defaultState), {
wrapper: ({ children }) =>
React.createElement(
React.Fragment,
null,
children,
React.createElement(Probe),
),
});

expect(order).toStrictEqual(['subscribe', 'layout', 'effect']);
});

describe('few instances', () => {
test('should set initial value only 1 time', () => {
const defaultState = { count: 0 };
Expand Down
14 changes: 6 additions & 8 deletions packages/urlstate/useSharedState/useSharedState.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';

import { stateMap, subscribers } from '../subscribers';
import { useInsertionEffect } from '../useInsertionEffect';
import { useIsomorphicLayoutEffect } from '../useIsomorphicLayoutEffect';
import { isEqual, isSSR, type JSONCompatible } from '../utils';

/**
Expand Down Expand Up @@ -65,18 +65,16 @@ export function useSharedState<T extends JSONCompatible>(
[],
);

useInsertionEffect(() => {
useIsomorphicLayoutEffect(() => {
const cb = () => {
_setState(stateMap.get(stateShape.current) || stateShape.current);
};
return subscribers.add(stateShape.current, cb);
}, []);
const unsubscribe = subscribers.add(stateShape.current, cb);

// stateMap can change between render and subscribing; that write skips this
// instance, and later ones compare against the map, so it never catches up.
// Same object back when nothing changed, React bails out on identity.
React.useEffect(() => {
// catch a write that landed between render and subscribing
_setState((curr) => stateMap.get(stateShape.current) ?? curr);

return unsubscribe;
}, []);

// get state without deps
Expand Down
77 changes: 67 additions & 10 deletions packages/urlstate/useUrlStateBase/useUrlStateBase.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import React from 'react';
import { act, fireEvent, renderHook } from '@testing-library/react';

// import { advanceTimersByTime } from '../../../tests/testUtils';
Expand Down Expand Up @@ -556,17 +557,12 @@ describe('useUrlStateBase', () => {
describe('back/forward history navigation', () => {
test('should update state on back/forward', () => {
vi.mocked(utils).isSSR = false;
const search = '?num=55';
const originalLocation = window.location;
vi
.spyOn(window, 'location', 'get')
.mockImplementationOnce(() => ({
...originalLocation,
}))
.mockImplementationOnce(() => ({
...originalLocation,
search,
}));
let search = '';
vi.spyOn(window, 'location', 'get').mockImplementation(() => ({
...originalLocation,
search,
}));
const { result } = renderHook(() =>
useUrlStateBase(shape, router, ({ parse }) =>
parse(window.location.search),
Expand All @@ -575,11 +571,72 @@ describe('useUrlStateBase', () => {

expect(result.current.state).toStrictEqual(shape);

search = '?num=55';
act(() => {
fireEvent.popState(window);
});
expect(result.current.state).toStrictEqual({ ...shape, num: 55 });
});

test('should pick up a popstate that fired before the listener registered', () => {
vi.mocked(utils).isSSR = false;
const originalLocation = window.location;
let search = '';
vi.spyOn(window, 'location', 'get').mockImplementation(() => ({
...originalLocation,
search,
}));

// renders after the hook, so the url moves before it listens
const UrlChangedMidRender = () => {
search = '?num=55';
return null;
};
const { result } = renderHook(
() =>
useUrlStateBase(shape, router, ({ parse }) =>
parse(window.location.search),
),
{
wrapper: ({ children }) =>
React.createElement(
React.Fragment,
null,
children,
React.createElement(UrlChangedMidRender),
),
},
);

expect(result.current.state).toStrictEqual({ ...shape, num: 55 });
});

test('should keep an updateState-only value when the url did not move', () => {
vi.mocked(utils).isSSR = false;
const originalLocation = window.location;
vi.spyOn(window, 'location', 'get').mockImplementation(() => ({
...originalLocation,
search: '',
}));
const { result } = renderHook(() =>
useUrlStateBase(shape, router, ({ parse }) =>
parse(window.location.search),
),
);

act(() => {
result.current.updateState({ num: 55 });
});

const second = renderHook(() =>
useUrlStateBase(shape, router, ({ parse }) =>
parse(window.location.search),
),
);

expect(second.result.current.state).toStrictEqual({ ...shape, num: 55 });
expect(result.current.state).toStrictEqual({ ...shape, num: 55 });
});
});

describe('basename prop', () => {
Expand Down
11 changes: 9 additions & 2 deletions packages/urlstate/useUrlStateBase/useUrlStateBase.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';

import { TIMEOUT } from '../constants';
import { useInsertionEffect } from '../useInsertionEffect';
import { useIsomorphicLayoutEffect } from '../useIsomorphicLayoutEffect';
import { useSharedState } from '../useSharedState';
import { useUrlEncode } from '../useUrlEncode';
import {
Expand Down Expand Up @@ -78,14 +78,21 @@ export function useUrlStateBase<T extends JSONCompatible>(
}) || defaultState,
);

useInsertionEffect(() => {
const searchAtRender = React.useRef<string>();
if (searchAtRender.current === undefined)
searchAtRender.current = getSearch();

useIsomorphicLayoutEffect(() => {
// for history navigation
const popCb = () => {
setState(parse(filterUnknownParamsClient(defaultState, getSearch())));
};

window.addEventListener(popstateEv, popCb);

// popstate before registration is not replayed
if (searchAtRender.current !== getSearch()) popCb();

return () => {
window.removeEventListener(popstateEv, popCb);
};
Expand Down
32 changes: 31 additions & 1 deletion packages/urlstate/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getParams, typeOf, assignValue, filterUnknownParamsClient, filterUnknown, filterUnknownParams, isPrimitive, getSearch } from './utils';
import { getParams, typeOf, assignValue, filterUnknownParamsClient, filterUnknown, filterUnknownParams, isPrimitive, getSearch, subscribeToUrl } from './utils';

describe('typeOf', () => {
test('string', () => {
Expand Down Expand Up @@ -391,3 +391,33 @@ describe('getSearch', () => {
});
});
});

describe('subscribeToUrl', () => {
test('notifies after the pushState call returns, not inside it', async () => {
const cb = vi.fn();
const originalHref = window.location.href;
const unsubscribe = subscribeToUrl(cb);

try {
window.history.pushState(null, '', '/sub?a=1');
expect(cb).not.toHaveBeenCalled();

await Promise.resolve();
expect(cb).toHaveBeenCalledTimes(1);

window.history.replaceState(null, '', '/sub?a=2');
expect(cb).toHaveBeenCalledTimes(1);

await Promise.resolve();
expect(cb).toHaveBeenCalledTimes(2);

unsubscribe();
window.history.pushState(null, '', '/sub?a=3');
await Promise.resolve();
expect(cb).toHaveBeenCalledTimes(2);
} finally {
unsubscribe();
window.history.replaceState(null, '', originalHref);
}
});
Comment thread
asmyshlyaev177 marked this conversation as resolved.
});
7 changes: 5 additions & 2 deletions packages/urlstate/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,8 +243,11 @@ function patchHistory() {
...args: Parameters<History['pushState']>
) {
const result = original.apply(this, args);
// copy, a listener can unsubscribe while iterating
for (const cb of [...urlListeners]) cb();
// Next writes history from a useInsertionEffect, which must not schedule updates
queueMicrotask(() => {
// copy, a listener can unsubscribe while iterating
for (const cb of [...urlListeners]) cb();
});
return result;
};
}
Expand Down