Skip to content

Commit 0f5b493

Browse files
committed
Merge pull request #2137 from schnerd/query-trigger-hooks
Call transition hooks when query changes for useQueries
2 parents 3fc8c6d + 6161e21 commit 0f5b493

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

modules/__tests__/transitionHooks-test.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import expect, { spyOn } from 'expect'
44
import React from 'react'
55
import createHistory from 'history/lib/createMemoryHistory'
6+
import useQueries from 'history/lib/useQueries'
67
import execSteps from './execSteps'
78
import Router from '../Router'
89

@@ -193,4 +194,19 @@ describe('When a router enters a branch', function () {
193194
})
194195
})
195196

197+
describe('and then the query changes', function () {
198+
it('calls the onEnter hooks of all routes in that branch', function (done) {
199+
const newsFeedRouteEnterSpy = spyOn(NewsFeedRoute, 'onEnter').andCallThrough()
200+
const history = useQueries(createHistory)('/inbox')
201+
202+
React.render(<Router history={history} routes={routes}/>, node, function () {
203+
history.pushState(null, '/news', { q: 1 })
204+
expect(newsFeedRouteEnterSpy.calls.length).toEqual(1)
205+
history.pushState(null, '/news', { q: 2 })
206+
expect(newsFeedRouteEnterSpy.calls.length).toEqual(2)
207+
done()
208+
})
209+
})
210+
})
211+
196212
})

modules/computeChangedRoutes.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,17 @@ function routeParamsChanged(route, prevState, nextState) {
1111
})
1212
}
1313

14+
function routeQueryChanged(prevState, nextState) {
15+
return prevState.location.search !== nextState.location.search
16+
}
17+
1418
/**
1519
* Returns an object of { leaveRoutes, enterRoutes } determined by
1620
* the change from prevState to nextState. We leave routes if either
1721
* 1) they are not in the next state or 2) they are in the next state
18-
* but their params have changed (i.e. /users/123 => /users/456).
22+
* but their params have changed (i.e. /users/123 => /users/456) or
23+
* 3) they are in the next state but the query has changed
24+
* (i.e. /search?query=foo => /search?query=bar)
1925
*
2026
* leaveRoutes are ordered starting at the leaf route of the tree
2127
* we're leaving up to the common parent route. enterRoutes are ordered
@@ -28,7 +34,9 @@ function computeChangedRoutes(prevState, nextState) {
2834
let leaveRoutes, enterRoutes
2935
if (prevRoutes) {
3036
leaveRoutes = prevRoutes.filter(function (route) {
31-
return nextRoutes.indexOf(route) === -1 || routeParamsChanged(route, prevState, nextState)
37+
return nextRoutes.indexOf(route) === -1
38+
|| routeParamsChanged(route, prevState, nextState)
39+
|| routeQueryChanged(prevState, nextState)
3240
})
3341

3442
// onLeave hooks start at the leaf route.

0 commit comments

Comments
 (0)