From 941011f9ea5a7bf142ffccc574cc9ea285faa427 Mon Sep 17 00:00:00 2001 From: simonihmig Date: Thu, 13 Aug 2020 10:26:23 +0200 Subject: [PATCH] Fix updateNode being called with undefined rootNode When redux `dispatch()` is called before `getState()` has ever been called, `updateNode()` (in the custom `creatStore()` function) will be called with `rootNode` still undefined. This wasn't catched in tests as they coincidentally always called `getState()` (for the cache setup) before dispatching. The added test here reproduces the bug that I was seeing when that's not the case. --- src/-private/create-store.ts | 11 +++++++---- tests/unit/basic-test.js | 10 +++++++++- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/-private/create-store.ts b/src/-private/create-store.ts index 01c6d2b..ea97f74 100644 --- a/src/-private/create-store.ts +++ b/src/-private/create-store.ts @@ -31,20 +31,23 @@ export default function createStore( ); const originalGetState = store.getState.bind(store); - - let rootNode; - - store.getState = (): S => { + const ensureRootNode = (): void => { if (rootNode === undefined) { rootNode = createNode({ state: originalGetState(), }); } + } + let rootNode; + + store.getState = (): S => { + ensureRootNode(); return rootNode.proxy.state; }; store.subscribe(() => { + ensureRootNode(); updateNode(rootNode, { state: originalGetState(), }); diff --git a/tests/unit/basic-test.js b/tests/unit/basic-test.js index 4b58d09..8f799fa 100644 --- a/tests/unit/basic-test.js +++ b/tests/unit/basic-test.js @@ -25,7 +25,15 @@ function createCache(fn) { module('Unit | basic', () => { module('primitive root', () => { - test('it works', (assert) => { + test('redux works', (assert) => { + let store = createStore((state = 0) => ++state); + + store.dispatch({ type: 'INCREMENT' }); + + assert.equal(store.getState(), 2, 'value is correct'); + }); + + test('caching works', (assert) => { let store = createStore((state = 0) => ++state); let cache = createCache(() => store.getState());