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

fixed connect issue with stale props (zombie children) #184

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
fixed connect issue with stale props (zombie children)
  • Loading branch information
azzurro committed Feb 4, 2020
commit 6f88c133d4a21e7b1de1dab140c2627774a6b4e0
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,15 @@
"bundlesize": [
{
"path": "full/preact.js",
"maxSize": "760b"
"maxSize": "850b"
},
{
"path": "dist/unistore.js",
"maxSize": "400b"
},
{
"path": "preact.js",
"maxSize": "600b"
"maxSize": "700b"
}
],
"babel": {
Expand Down
24 changes: 4 additions & 20 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { assign } from './util';
import createSubscriber from './subscriber';

/**
* Creates a new store, which is a tiny evented state container.
Expand All @@ -12,26 +13,12 @@ import { assign } from './util';
* store.setState({ c: 'd' }); // logs { a: 'b', c: 'd' }
*/
export default function createStore(state) {
let listeners = [];
const { emit, subscribe, unsubscribe } = createSubscriber();
state = state || {};

function unsubscribe(listener) {
let out = [];
for (let i=0; i<listeners.length; i++) {
if (listeners[i]===listener) {
listener = null;
}
else {
out.push(listeners[i]);
}
}
listeners = out;
}

function setState(update, overwrite, action) {
state = overwrite ? update : assign(assign({}, state), update);
let currentListeners = listeners;
for (let i=0; i<currentListeners.length; i++) currentListeners[i](state, action);
emit(state, action);
}

/**
Expand Down Expand Up @@ -77,10 +64,7 @@ export default function createStore(state) {
* @param {Function} listener A function to call when state changes. Gets passed the new state.
* @returns {Function} unsubscribe()
*/
subscribe(listener) {
listeners.push(listener);
return () => { unsubscribe(listener); };
},
subscribe,

/**
* Remove a previously-registered listener function.
Expand Down
5 changes: 5 additions & 0 deletions src/integrations/preact.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { h, Component } from 'preact';
import createSubscriber from '../subscriber';
import { assign, mapActions, select } from '../util';

/**
Expand All @@ -22,6 +23,8 @@ export function connect(mapStateToProps, actions) {
return Child => {
function Wrapper(props, context) {
const store = context.store;
const { emit, subscribe, unsubscribe } = createSubscriber();
const subStore = { ...store, subscribe, unsubscribe };
let state = mapStateToProps(store ? store.getState() : {}, props);
const boundActions = actions ? mapActions(actions, store) : { store };
let update = () => {
Expand All @@ -34,6 +37,7 @@ export function connect(mapStateToProps, actions) {
state = mapped;
return this.setState({});
}
emit();
};
this.componentWillReceiveProps = p => {
props = p;
Expand All @@ -45,6 +49,7 @@ export function connect(mapStateToProps, actions) {
this.componentWillUnmount = () => {
store.unsubscribe(update);
};
this.getChildContext = () => ({ store: subStore });
this.render = props => h(Child, assign(assign(assign({}, boundActions), props), state));
}
return (Wrapper.prototype = new Component()).constructor = Wrapper;
Expand Down
6 changes: 6 additions & 0 deletions src/integrations/react.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createElement, Children, Component } from 'react';
import createSubscriber from '../subscriber';
import { assign, mapActions, select } from '../util';

const CONTEXT_TYPES = {
Expand Down Expand Up @@ -26,6 +27,8 @@ export function connect(mapStateToProps, actions) {
function Wrapper(props, context) {
Component.call(this, props, context);
const store = context.store;
const { emit, subscribe, unsubscribe } = createSubscriber();
const subStore = { ...store, subscribe, unsubscribe };
let state = mapStateToProps(store ? store.getState() : {}, props);
const boundActions = actions ? mapActions(actions, store) : { store };
let update = () => {
Expand All @@ -38,6 +41,7 @@ export function connect(mapStateToProps, actions) {
state = mapped;
return this.forceUpdate();
}
emit();
};
this.componentWillReceiveProps = p => {
props = p;
Expand All @@ -49,8 +53,10 @@ export function connect(mapStateToProps, actions) {
this.componentWillUnmount = () => {
store.unsubscribe(update);
};
this.getChildContext = () => ({ store: subStore });
this.render = () => createElement(Child, assign(assign(assign({}, boundActions), this.props), state));
}
Wrapper.childContextTypes = CONTEXT_TYPES;
Wrapper.contextTypes = CONTEXT_TYPES;
return (Wrapper.prototype = Object.create(Component.prototype)).constructor = Wrapper;
};
Expand Down
35 changes: 35 additions & 0 deletions src/subscriber.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
export default function createSubscriber() {
let listeners = [];

// Remove a previously-registered listener function.
function unsubscribe(listener) {
let out = [];
for (let i=0; i<listeners.length; i++) {
if (listeners[i]===listener) {
listener = null;
}
else {
out.push(listeners[i]);
}
}
listeners = out;
}

return {
// Calls registered listeners with given arguments.
emit() {
let currentListeners = listeners;
for (let i=0; i<currentListeners.length; i++) {
currentListeners[i].apply(null, arguments);
}
},

// Register a listener function to be called whenever state is changed. Returns an `unsubscribe()` function.
subscribe(listener) {
listeners.push(listener);
return () => { unsubscribe(listener); };
},

unsubscribe
};
}
44 changes: 44 additions & 0 deletions test/preact/preact.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -211,5 +211,49 @@ describe(`integrations/preact${global.IS_PREACT_8 ? '-8' : ''}`, () => {
expect.anything()
);
});

it('should ignore stale props (zombie children)', async () => {
const orgState = {obj: {foo: 1, bar: 2}, current: 'foo'}
const store = createStore(orgState);
const Child = ({num}) => <div>{num}</div>;
const mapStateToProps = jest.fn((state, {id}) => ({num: state.obj[id]}));
const ConnectedChild = connect(mapStateToProps)(Child);
const Parent = jest.fn(({current}) => <ConnectedChild id={current} />);
const ConnectedParent = connect('current')(Parent);

render(
<Provider store={store}>
<ConnectedParent />
</Provider>,
document.body
);

expect(mapStateToProps).toHaveBeenCalledTimes(1);
expect(mapStateToProps).toHaveBeenCalledWith(
orgState, {children: NO_CHILDREN, id: 'foo'});
expect(Parent).toHaveBeenCalledTimes(1);

mapStateToProps.mockClear();
Parent.mockClear();
store.setState({current: 'bar'});
await sleep(1);

// Should only call the child mapStateToProps once (thru parent render).
expect(mapStateToProps).toHaveBeenCalledTimes(1);
expect(mapStateToProps).toHaveBeenCalledWith(
{...orgState, current: 'bar'}, {children: NO_CHILDREN, id: 'bar'});
expect(Parent).toHaveBeenCalledTimes(1);

mapStateToProps.mockClear();
Parent.mockClear();
store.setState({obj: {foo: 1, bar: 3}});
await sleep(1);

// Should only call the child mapStateToProps once (ignoring parent render).
expect(mapStateToProps).toHaveBeenCalledTimes(1);
expect(mapStateToProps).toHaveBeenCalledWith(
{obj: {foo: 1, bar: 3}, current: 'bar'}, {children: NO_CHILDREN, id: 'bar'});
expect(Parent).not.toHaveBeenCalled();
});
});
});
42 changes: 42 additions & 0 deletions test/react/react.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -184,4 +184,46 @@ describe('integrations/react', () => {
expect.anything()
);
});

it('should ignore stale props (zombie children)', async () => {
const orgState = {obj: {foo: 1, bar: 2}, current: 'foo'}
const store = createStore(orgState);
const Child = ({num}) => <div>{num}</div>;
const mapStateToProps = jest.fn((state, {id}) => ({num: state.obj[id]}));
const ConnectedChild = connect(mapStateToProps)(Child);
const Parent = jest.fn(({current}) => <ConnectedChild id={current} />);
const ConnectedParent = connect('current')(Parent);

mount(
<Provider store={store}>
<ConnectedParent />
</Provider>
);

expect(mapStateToProps).toHaveBeenCalledTimes(1);
expect(mapStateToProps).toHaveBeenCalledWith(orgState, {id: 'foo'});
expect(Parent).toHaveBeenCalledTimes(1);

mapStateToProps.mockClear();
Parent.mockClear();
store.setState({current: 'bar'});
await sleep(1);

// Should only call the child mapStateToProps once (thru parent render).
expect(mapStateToProps).toHaveBeenCalledTimes(1);
expect(mapStateToProps).toHaveBeenCalledWith(
{...orgState, current: 'bar'}, {id: 'bar'});
expect(Parent).toHaveBeenCalledTimes(1);

mapStateToProps.mockClear();
Parent.mockClear();
store.setState({obj: {foo: 1, bar: 3}});
await sleep(1);

// Should only call the child mapStateToProps once (ignoring parent render).
expect(mapStateToProps).toHaveBeenCalledTimes(1);
expect(mapStateToProps).toHaveBeenCalledWith(
{obj: {foo: 1, bar: 3}, current: 'bar'}, {id: 'bar'});
expect(Parent).not.toHaveBeenCalled();
});
});