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

fix: should add subscribe after hot load #13

Open
wants to merge 4 commits into
base: v0.2.x
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
],
"scripts": {
"clean": "rm -rf dist",
"dev": "rollup -w --config rollup.config.js",
"bundle": "rollup --config rollup.config.js",
"build": "run-s clean bundle",
"test": "jest",
Expand Down
13 changes: 9 additions & 4 deletions src/hooks.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,17 @@ describe('useSelector', () => {
const defaultSelector = selector(defaultFn);
const strictSelector = selector(strictFn, (select, times) => [select(testBox).count, times]);
const inlineFn = fn((select: Select) => select(testBox).count);
const expectCalled = (isDefault: boolean, isStrict: boolean, isInline: boolean) => {
const expectCalled = (
isDefault: boolean,
isStrict: boolean,
isInline: boolean,
first?: boolean,
) => {
expect(defaultFn).toBeCalledTimes(isDefault ? 1 : 0);
defaultFn.mockClear();
expect(strictFn).toBeCalledTimes(isStrict ? 1 : 0);
expect(strictFn).toBeCalledTimes(isStrict ? (first ? 2 : 1) : 0);
strictFn.mockClear();
expect(inlineFn).toBeCalledTimes(isInline ? 1 : 0);
expect(inlineFn).toBeCalledTimes(isInline ? (first ? 2 : 1) : 0);
inlineFn.mockClear();
};
const { result, dispatch, rerender, waitForNextUpdate } = renderUseSelector(
Expand All @@ -99,7 +104,7 @@ describe('useSelector', () => {
{ count: 1, test: { count: 1, greets: ['PRELOAD'] } },
{ multiply: 1 },
);
expectCalled(true, true, true);
expectCalled(true, true, true, true);
expect(result.current).toEqual([1, 1, 1, 1]);
dispatch(addGreet('HELLO'));
await waitForNextUpdate();
Expand Down
105 changes: 66 additions & 39 deletions src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,19 @@
* @author acrazing <[email protected]>
*/

import { useContext, useDebugValue, useEffect, useReducer, useRef } from 'react';
import { useContext, useDebugValue, useLayoutEffect, useEffect, useReducer, useRef } from 'react';
import { __Context } from './context';
import { Selector } from './selector';
import { Dispatch, Selectable, Snapshot, Store } from './store';
import { arrayEqual, strictEqual } from './utils';

export const useIsomorphicLayoutEffect =
typeof window !== 'undefined' &&
typeof window.document !== 'undefined' &&
typeof window.document.createElement !== 'undefined'
? useLayoutEffect
: useEffect;

/**
* use context's store
*
Expand Down Expand Up @@ -158,9 +165,58 @@ export function useSelector<Rs extends Selectable[]>(...selectors: Rs): MapSelec
const store = useStore();
const lastSelector = useRef<SelectorRef>(defaultSelectorRef);
const lastStore = useRef<StoreRef>();
const lastState = useRef<unknown[]>([]);

if (lastStore.current?.store !== store) {
lastSelector.current = defaultSelectorRef;
lastStore.current?.disposer();
}

if (lastStore.current?.error) {
const error = lastStore.current.error;
lastStore.current.error = void 0;
throw error;
}

const resolveState = () => {
if (lastStore.current?.updated) {
lastStore.current.updated = false;
return lastSelector.current.results;
} else {
if (lastSelector.current === defaultSelectorRef) {
lastSelector.current = { selectors: [], deps: [], snapshots: [], results: [] };
}
// updates from outside
const { selectors: oldSelectors, deps, snapshots, results } = lastSelector.current;
for (let i = 0; i < selectors.length; i++) {
const old = oldSelectors[i];
const newly = selectors[i];
if (typeof newly === 'object') {
results[i] = store.select(newly);
oldSelectors[i] = newly;
} else {
const newDeps = selectorChanged(old, newly, snapshots[i], store, deps[i]);
if (newDeps) {
snapshots[i] = void 0;
const newSnapshot: Snapshot = {};
results[i] = store.select(newly, newSnapshot);
deps[i] = newDeps === true ? void 0 : newDeps;
snapshots[i] = newSnapshot;
oldSelectors[i] = newly;
}
}
}
results.length = selectors.length;
return results;
}
};

let selectedState: any = resolveState();

useIsomorphicLayoutEffect(() => {
lastState.current = [...selectedState];
});

useIsomorphicLayoutEffect(() => {
lastStore.current = {
store,
updated: false,
Expand Down Expand Up @@ -200,44 +256,15 @@ export function useSelector<Rs extends Selectable[]>(...selectors: Rs): MapSelec
}
}),
};
}
useEffect(() => () => lastStore.current?.disposer(), []);
if (lastStore.current.error) {
const error = lastStore.current.error;
lastStore.current.error = void 0;
throw error;
}
let selectedState: any;
if (lastStore.current.updated) {
lastStore.current.updated = false;
selectedState = lastSelector.current.results;
} else {
if (lastSelector.current === defaultSelectorRef) {
lastSelector.current = { selectors: [], deps: [], snapshots: [], results: [] };
}
// updates from outside
const { selectors: oldSelectors, deps, snapshots, results } = lastSelector.current;
for (let i = 0; i < selectors.length; i++) {
const old = oldSelectors[i];
const newly = selectors[i];
if (typeof newly === 'object') {
results[i] = store.select(newly);
oldSelectors[i] = newly;
} else {
const newDeps = selectorChanged(old, newly, snapshots[i], store, deps[i]);
if (newDeps) {
snapshots[i] = void 0;
const newSnapshot: Snapshot = {};
results[i] = store.select(newly, newSnapshot);
deps[i] = newDeps === true ? void 0 : newDeps;
snapshots[i] = newSnapshot;
oldSelectors[i] = newly;
}
}

// if something change between render and the effect. eg. dispatch when render
if (!arrayEqual(lastState.current, resolveState())) {
update();
}
results.length = selectors.length;
selectedState = results;
}

return () => lastStore.current?.disposer();
}, [store]);

// TODO: print friendly with selector names
useDebugValue(selectedState, (value: any[]) => {
return value.reduce((map, value, index) => {
Expand Down