Skip to content
This repository was archived by the owner on Oct 26, 2018. It is now read-only.

Split history syncing from action creators #259

Merged
merged 38 commits into from
Feb 17, 2016
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
7cdc72a
Extract the action creators and middleware.
timdorr Feb 5, 2016
2946938
Pull in @gaearon's history syncer.
timdorr Feb 5, 2016
21b511b
Go with Babel Stage 1 for export extensions.
timdorr Feb 5, 2016
fbe174f
Update the example against the new API.
timdorr Feb 5, 2016
88bc0de
Minor reorg. Split the reducer to its own file.
timdorr Feb 5, 2016
a2ec57b
Fix linting in example.
timdorr Feb 5, 2016
36845f5
Hollow out the old tests and fill in something basic.
timdorr Feb 5, 2016
10e34d2
Update build script for multi-file setup.
timdorr Feb 5, 2016
4c17b0e
Clean up some testing framework stuff.
timdorr Feb 5, 2016
c61c92c
Use spread instead Object.assign. Following #259
webmasterkai Feb 6, 2016
4afd74f
Confirm location change before listener invokation
webmasterkai Feb 6, 2016
fc12f70
Begin updating example in README. Re #259
webmasterkai Feb 6, 2016
1a8c800
README syncHistory becomes syncHistoryWithStore
webmasterkai Feb 6, 2016
08b3818
Merge pull request #262 from webmasterkai/synchronicity
timdorr Feb 6, 2016
379dc9c
Add back route action tests.
timdorr Feb 6, 2016
def06ff
Add reducer tests. Ensure actions are FSA.
timdorr Feb 6, 2016
2b177f5
Add middleware test. Reorg test suite.
timdorr Feb 6, 2016
2c88667
rename UPDATE_LOCATION to CALL_HISTORY_METHOD
webmasterkai Feb 6, 2016
a452791
Merge pull request #265 from webmasterkai/actionTypeAlt
timdorr Feb 6, 2016
cb9d6b6
Redone docs.
timdorr Feb 7, 2016
50faa62
Add a note warning about reading from store.
timdorr Feb 7, 2016
4308208
Add back some other relevant tests.
timdorr Feb 7, 2016
0b7b322
Add docs for syncHistoryWithStore's options.
timdorr Feb 8, 2016
9b2dc36
Don't leave test side effects with history singltons.
timdorr Feb 8, 2016
820f46e
4.0.0-beta.1
timdorr Feb 8, 2016
8ed23ca
Merge remote-tracking branch 'origin/master' into synchronicity
timdorr Feb 10, 2016
98ceca0
Merge remote-tracking branch 'origin/master' into synchronicity
timdorr Feb 12, 2016
f0e09db
docs(readme): add example migration from ^3.0.0
Feb 12, 2016
d54496c
Merge pull request #271 from davezuko/patch-2
timdorr Feb 12, 2016
d45f1c6
Update README.md
justin808 Feb 14, 2016
60fa049
Merge pull request #278 from justin808/patch-2
timdorr Feb 14, 2016
8bc27b9
Merge remote-tracking branch 'origin/master' into synchronicity
timdorr Feb 15, 2016
cdc941d
Switch to run example on webpack-dev-server.
timdorr Feb 15, 2016
31b3809
added example to readme
svrcekmichal Feb 15, 2016
d2e5173
Merge pull request #280 from svrcekmichal/synchronicity
timdorr Feb 15, 2016
67aefaa
Merge remote-tracking branch 'origin/master' into synchronicity
timdorr Feb 15, 2016
87402ea
Add a SSR example.
timdorr Feb 17, 2016
8d4750e
Merge remote-tracking branch 'origin/master' into synchronicity
timdorr Feb 17, 2016
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
34 changes: 12 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ View the [CHANGELOG](https://github.com/rackt/react-router-redux/blob/master/CHA

Read the [API docs](#api) farther down this page.

**Note:** We are [currently discussing some major changes](https://github.com/rackt/react-router-redux/issues/257) to the library. [React Router's API in 2.0](https://github.com/rackt/react-router/blob/master/upgrade-guides/v2.0.0.md) is significantly improved and obseletes the need for things like action creators and reading location state from the Redux. This library is still critical to enable things like time traveling and persisting state, so we're not going anywhere. But in many cases, you may not need this library and can simply use the provided React Router APIs. Go check them out and drop some technical debt. :smile:
**Note:** We are [currently discussing some major changes](https://github.com/rackt/react-router-redux/issues/257) to the library. [React Router's API in 2.0](https://github.com/rackt/react-router/blob/master/upgrade-guides/v2.0.0.md) is significantly improved and makes things like action creators and reading location state from Redux obsolete. This library is still critical to enable things like time traveling and persisting state, so we're not going anywhere. But in many cases, you may not need this library and can simply use the provided React Router APIs. Go check them out and drop some technical debt. :smile:

### Usage

Expand All @@ -44,25 +44,25 @@ import ReactDOM from 'react-dom'
import { createStore, combineReducers, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import { Router, Route, browserHistory } from 'react-router'
import { syncHistory, routeReducer } from 'react-router-redux'
import { syncHistoryWithStore, routerReducer } from 'react-router-redux'

import reducers from '<project-path>/reducers'

const reducer = combineReducers(Object.assign({}, reducers, {
routing: routeReducer
routing: routerReducer
}))

// Sync dispatched route actions to the history
const reduxRouterMiddleware = syncHistory(browserHistory)
const createStoreWithMiddleware = applyMiddleware(reduxRouterMiddleware)(createStore)
const store = createStore(reducer)

const store = createStoreWithMiddleware(reducer)
// Sync dispatched route actions to the history
Copy link
Member

Choose a reason for hiding this comment

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

TODO:

I think this comment should be backwards. We are not syncing "route actions to history". We are syncing history changes to the store. Or "using store as source of truth for the history". Or "routing history changes through the store".

Saying that we "sync dispatched actions to history" is a misleading leftover comment from how it used to work.

Copy link
Member Author

Choose a reason for hiding this comment

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

The whole thing needs to be reworked. I'll likely just scrap it and restart from scratch.

const history = syncHistoryWithStore(browserHistory, store)

// Required for replaying actions from devtools to work
reduxRouterMiddleware.listenForReplays(store)

ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}>
<Router history={history}>
<Route path="/" component={App}>
<Route path="foo" component={Foo}/>
<Route path="bar" component={Bar}/>
Expand All @@ -73,7 +73,7 @@ ReactDOM.render(
)
```

Now you can read from `state.routing.location.pathname` to get the URL. It's far more likely that you want to change the URL more often, however. You can use the `push` action creator that we provide:
Now you can read from `state.routing.locationBeforeTransitions.pathname` to get the URL. It's far more likely that you want to change the URL more often, however. You can use the `push` action creator that we provide:
Copy link
Member

Choose a reason for hiding this comment

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

Here we should warn why it's called so. In particular that it may not reflect the current UI state, and that we don't recommend reading it from the UI of the user also uses async transitions.


```js
import { routeActions } from 'react-router-redux'
Expand Down Expand Up @@ -132,21 +132,11 @@ _Have an example to add? Send us a PR!_

### API

#### `syncHistory(history: History) => ReduxMiddleware`

Call this to create a middleware that can be applied with Redux's `applyMiddleware` to allow actions to call history methods. The middleware will look for route actions created by `push`, `replace`, etc. and applies them to the history.

#### `ReduxMiddleware.listenForReplays(store: ReduxStore, selectLocationState?: function)`

By default, the syncing logic will not respond to replaying of actions, which means it won't work with projects like redux-devtools. Call this function on the middleware object returned from `syncHistory` and give it the store to listen to, and it will properly work with action replays. Obviously, you would do that after you have created the store and everything else has been set up.

Supply an optional function `selectLocationState` to customize where to find the location state on your app state. It defaults to `state => state.routing.location`, so you would install the reducer under the name "routing". Feel free to change this to whatever you like.

#### `ReduxMiddleware.unsubscribe()`
#### `history = syncHistoryWithStore(history: History, store)`

Call this on the middleware returned from `syncHistory` to stop the syncing process set up by `listenForReplays`.
We now sync by enhancing the history instance to listen for navigation events and dispatch those into the store. The enhanced history has its listen method overridden to respond to store changes, rather than directly to navigation events. When this history is provided to <Router>, the router will listen to it and receive these store changes. This means if we time travel with the store, the router will receive those store changes and update based on the location in the store, instead of what the browser says. Normal navigation events (hitting your browser back/forward buttons, telling a history singleton to push a location) flow through the history's listener like normal, so all the usual stuff works A-OK.

#### `routeReducer`
#### `routerReducer`

A reducer function that keeps track of the router state. You must add this reducer to your app reducers when creating the store. It will return a `location` property in state. If you use `combineReducers`, it will be nested under wherever property you add it to (`state.routing` in the example above).

Expand Down
24 changes: 16 additions & 8 deletions src/sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,10 @@ export default function syncHistoryWithStore(history, store, {
// Update address bar to reflect store state
isTimeTraveling = true
currentLocation = locationInStore
history.transitionTo(Object.assign({},
locationInStore,
{ action: 'PUSH' }
))
history.transitionTo({
...locationInStore,
action: 'PUSH'
})
isTimeTraveling = false
}

Expand Down Expand Up @@ -95,18 +95,26 @@ export default function syncHistoryWithStore(history, store, {
unsubscribeFromHistory = history.listen(handleLocationChange)

// The enhanced history uses store as source of truth
return Object.assign({}, history, {
return {
...history,
// The listeners are subscribed to the store instead of history
listen(listener) {
// Copy of last location.
let lastPublishedLocation = getLocationInStore(true)
// History listeners expect a synchronous call
listener(getLocationInStore(true))
listener(lastPublishedLocation)

// Keep track of whether we unsubscribed, as Redux store
// only applies changes in subscriptions on next dispatch
let unsubscribed = false
const unsubscribeFromStore = store.subscribe(() => {
const currentLocation = getLocationInStore(true)
if (currentLocation === lastPublishedLocation) {
return
}
lastPublishedLocation = currentLocation
if (!unsubscribed) {
listener(getLocationInStore(true))
listener(lastPublishedLocation)
}
})

Expand All @@ -124,5 +132,5 @@ export default function syncHistoryWithStore(history, store, {
}
unsubscribeFromHistory()
}
})
}
}