Skip to content

Commit

Permalink
proppy-redux: Call mapState when parentProps are received (#42)
Browse files Browse the repository at this point in the history
* Call mapState when parentProps are recieved

* Remove whitespace

* More whitespace

* Add test for withStore.handleReceivedProps

* Remove whitespace
  • Loading branch information
dakota authored and fahad19 committed Apr 13, 2019
1 parent 91af764 commit 057a3d7
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
71 changes: 71 additions & 0 deletions packages/proppy-redux/src/withStore.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* global describe, test, expect */
import { createStore, combineReducers } from 'redux';
import { withState } from 'proppy';

import { withStore } from './withStore';

Expand Down Expand Up @@ -76,4 +77,74 @@ describe('proppy-redux :: withStore', () => {

expect(p.props.counter).toEqual(1);
});

test('can receive updates', () => {
// constants
const INCREMENT_COUNTER = 'INCREMENT_COUNTER';
const DECREMENT_COUNTER = 'DECREMENT_COUNTER';

// actions
function incrementCounter(payload) {
return {
type: INCREMENT_COUNTER,
payload
};
}
function decrementCounter(payload) {
return {
type: DECREMENT_COUNTER,
payload
};
}
// reducers
const INITIAL_STATE = {};

function counterReducer(state = INITIAL_STATE, action) {
switch (action.type) {
case INCREMENT_COUNTER:
return Object.assign({}, state, {
[action.payload]: (state[action.payload] || 0) + 1
});
case DECREMENT_COUNTER:
return Object.assign({}, state, {
[action.payload]: (state[action.payload] || 0) - 1
});
default:
return state;
}
}

const rootReducer = combineReducers({
counter: counterReducer,
});

const store = createStore(rootReducer);

const P = withStore(
(state, providers, ownProps) => ({ counter: state.counter[ownProps.key] || 0 }),
{
increment: incrementCounter,
decrement: decrementCounter,
},
);
const parent = withState('key', 'setKey', 'counter1')();
const p = P({
store,
}, parent);

p.subscribe(() => {});

expect(p.props.counter).toEqual(0);

p.props.increment(p.props.key);
p.props.increment(p.props.key);

expect(p.props.counter).toEqual(2);

parent.props.setKey('Counter2');

expect(p.props.counter).toEqual(0);
p.props.increment(p.props.key);
expect(p.props.counter).toEqual(1);
});
});
11 changes: 11 additions & 0 deletions packages/proppy-redux/src/withStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,17 @@ export function withStore(
}
},

handleReceivedProps(parentProps) {
if (mapState) {
this.set(parentProps);
this.set(mapState.apply(this, [
this._store.getState(),
this.providers,
this.props,
]));
}
},

willDestroy() {
if (this._storeSubscription) {
this._storeSubscription();
Expand Down

0 comments on commit 057a3d7

Please sign in to comment.