Skip to content

tests and fixes #457 #472

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

Merged
merged 3 commits into from
Aug 27, 2016
Merged
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
69 changes: 44 additions & 25 deletions src/utils/Subscription.js
Original file line number Diff line number Diff line change
@@ -1,45 +1,61 @@
// encapsulates the subscription logic for connecting a component to the redux store, as
// well as nesting subscriptions of descendant components, so that we can ensure the
// ancestor components re-render before descendants
Copy link
Member

Choose a reason for hiding this comment

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

I know this is a bit out of scope, but perhaps we can mention the whole current/next setup below and why it's structured that way, now that all the code is in one spot right below this. It's not super-obvious why you would do that just reading through (do we have tests for Subscription? That would be another way of documenting it.)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The next/current pattern is straight out of the redux source. My hope is to eventually refactor that code into something reusable by the main store or Subscription.js

Copy link
Member

Choose a reason for hiding this comment

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

I know @acdlite wanted to do something like that in reduxjs/redux#1729, but it's gone inactive (although, @acdlite did just merge in some stuff on the upstream repo just a few hours ago...). Might be good to focus efforts there so we can use the exact same code in both places.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah. My thought was to wait until these changes have landed, take care of any outstanding issues and let the dust settle before further tinkering.


const CLEARED = null

function createListenerCollection() {
// the current/next pattern is copied from redux's createStore code.
// TODO: refactor+expose that code to be reusable here?
let current = []
let next = []

return {
clear() {
next = CLEARED
current = CLEARED
},

notify() {
current = next
for (let i = 0; i < current.length; i++) {
current[i]()
}
},

subscribe(listener) {
let isSubscribed = true
if (next === current) next = current.slice()
next.push(listener)

return function unsubscribe() {
if (!isSubscribed || current === CLEARED) return
isSubscribed = false

if (next === current) next = current.slice()
next.splice(next.indexOf(listener), 1)
}
}
}
}

export default class Subscription {
constructor(store, parentSub) {
this.subscribe = parentSub
? parentSub.addNestedSub.bind(parentSub)
: store.subscribe.bind(store)

this.unsubscribe = null
this.nextListeners = this.currentListeners = []
}

ensureCanMutateNextListeners() {
if (this.nextListeners === this.currentListeners) {
this.nextListeners = this.currentListeners.slice()
}
this.listeners = createListenerCollection()
}

addNestedSub(listener) {
this.trySubscribe()

let isSubscribed = true
this.ensureCanMutateNextListeners()
this.nextListeners.push(listener)

return function unsubscribe() {
if (!isSubscribed) return
isSubscribed = false

this.ensureCanMutateNextListeners()
const index = this.nextListeners.indexOf(listener)
this.nextListeners.splice(index, 1)
}
return this.listeners.subscribe(listener)
}

notifyNestedSubs() {
const listeners = this.currentListeners = this.nextListeners
const length = listeners.length
for (let i = 0; i < length; i++) {
listeners[i]()
}
this.listeners.notify()
}

isSubscribed() {
Expand All @@ -55,7 +71,10 @@ export default class Subscription {
tryUnsubscribe() {
if (this.unsubscribe) {
this.unsubscribe()
this.listeners.clear()
}
this.unsubscribe = null
this.subscribe = null
this.listeners = { notify() {} }
}
}
80 changes: 80 additions & 0 deletions test/components/connect.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -910,6 +910,86 @@ describe('React', () => {
expect(mapStateToPropsCalls).toBe(1)
})

it('should not attempt to set state after unmounting nested components', () => {
const store = createStore(() => ({}))
let mapStateToPropsCalls = 0

let linkA, linkB

let App = ({ children, setLocation }) => {
const onClick = to => event => {
event.preventDefault()
setLocation(to)
}
/* eslint-disable react/jsx-no-bind */
return (
<div>
<a href="#" onClick={onClick('a')} ref={c => { linkA = c }}>A</a>
<a href="#" onClick={onClick('b')} ref={c => { linkB = c }}>B</a>
{children}
</div>
)
/* eslint-enable react/jsx-no-bind */
}
App = connect(() => ({}))(App)


let A = () => (<h1>A</h1>)
A = connect(() => ({ calls: ++mapStateToPropsCalls }))(A)


const B = () => (<h1>B</h1>)


class RouterMock extends React.Component {
constructor(...args) {
super(...args)
this.state = { location: { pathname: 'a' } }
this.setLocation = this.setLocation.bind(this)
}

setLocation(pathname) {
this.setState({ location: { pathname } })
store.dispatch({ type: 'TEST' })
}

getChildComponent(location) {
switch (location) {
case 'a': return <A />
case 'b': return <B />
default: throw new Error('Unknown location: ' + location)
}
}

render() {
return (<App setLocation={this.setLocation}>
{this.getChildComponent(this.state.location.pathname)}
</App>)
}
}
Copy link
Member

Choose a reason for hiding this comment

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

From one of the react-router maintainers, this is a top quality mock router 😄

Copy link
Contributor

Choose a reason for hiding this comment

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

Agreed. Easy to extend as well for the next person who wants to hoist it and have it take a map of route to component.



const div = document.createElement('div')
document.body.appendChild(div)
ReactDOM.render(
(<ProviderMock store={store}>
<RouterMock />
</ProviderMock>),
div
)

const spy = expect.spyOn(console, 'error')

linkA.click()
linkB.click()
linkB.click()

spy.destroy()
document.body.removeChild(div)
expect(mapStateToPropsCalls).toBe(3)
expect(spy.calls.length).toBe(0)
})

it('should not attempt to set state when dispatching in componentWillUnmount', () => {
const store = createStore(stringBuilder)
let mapStateToPropsCalls = 0
Expand Down