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

Preserve state reference if unchanged and not in transaction #25

Merged
merged 4 commits into from
Mar 1, 2018
Merged
Show file tree
Hide file tree
Changes from 3 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
11 changes: 9 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,15 @@ function optimist(fn) {
return revertReducer(state, action);
}
}
let separated = separateState(state);
return baseReducer(separated.optimist, separated.innerState, action);

let {optimist, innerState} = separateState(state);
if (state) {
let nextState = fn(innerState, action);
if (nextState === innerState && !optimist.length) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think there are two new problems here:

  1. If optimist.length > 0 we should skip straight to baseReducer, not also run fn first.
  2. It looks like fn is potentially getting called twice here (if it applies a change). The fn should only ever be called once per action.

return state;
}
}
return baseReducer(optimist, innerState, action);
};
}

Expand Down
19 changes: 19 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,17 @@ basic('commit other transaction', {
}
});

test('omits optimist from original reducer', () => {
function originalReducer(state = {value: 0}, action) {
assert(state.value === 0);
assert(!state.hasOwnProperty('optimist'));
return state;
}
let reducer = optimist(originalReducer);
let state;
state = reducer(state, {type: 'foo'});
state = reducer(state, {type: 'foo'});
});

test('real world example', () => {
function originalReducer(state = {value: 0}, action) {
Expand Down Expand Up @@ -387,6 +398,14 @@ test('real world example 2', () => {
assert.deepEqual(state, {optimist: [], value: 4});
});

test('unhandled action state reference', () => {
let originalReducer = ( state = {} ) => state;
let reducer = optimist(originalReducer);
let initState = reducer(undefined, {type: '@@init'});
let originalState = reducer(initState, {type: 'UNHANDLED_ACTION'});
let nextState = reducer(originalState, {type: 'UNHANDLED_ACTION'});
assert.strictEqual(originalState, nextState);
});

function basic(name, {reducer, before, action, after}) {
test(name, () => {
Expand Down