Skip to content

Instantly share code, notes, and snippets.

@danharper
Last active August 29, 2015 14:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danharper/2a0d41434978b8bef061 to your computer and use it in GitHub Desktop.
Save danharper/2a0d41434978b8bef061 to your computer and use it in GitHub Desktop.
Mess to transition in async action creators for redux-react-router
import { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { transitionTo } from 'redux-react-router'
const NEXT_URL = 'REDIRECTOR(NEXT_URL)'
const CLEAR_NEXT_URL = 'REDIRECTOR(CLEAR_NEXT_URL)'
export const transitionNext = url => ({ type: NEXT_URL, payload: url })
export const clearNextUrl = () => ({ type: CLEAR_NEXT_URL })
export const redirectorReducer = (state = { nextUrl: null }, action) => {
switch (action.type) {
case NEXT_URL:
return { nextUrl: action.payload }
case CLEAR_NEXT_URL:
return { nextUrl: null }
default:
return state
}
}
@connect(state => ({ nextUrl: state.redirector.nextUrl }))
export class Redirector extends Component {
static propTypes = {
nextUrl: PropTypes.string,
dispatch: PropTypes.func.isRequired,
}
componentWillReceiveProps(nextProps) {
const { nextUrl, dispatch } = nextProps
if (nextUrl) {
dispatch(clearNextUrl())
dispatch(transitionTo(nextUrl))
}
}
render() {
return null
}
}

NOTE Haven't tested with more complex transitions, so I'm sure there's some things missing. Just works for what I currently need. May decide this is a bad idea in the morning...


Stick <Redirector /> somewhere in your state tree where it'll always be rendered (e.g. in a Container component).

Add the redirectorReducer reducer to your reducers as redirector, e.g.

import { routerStateReducer as router } from 'redux-react-router'
import { redirectorReducer as redirector } from './Redirector'

const reducers = combineReducers({
  router,
  redirector,
  // etc...
})

Then where you need to transition, use transitionNext:

import { transitionNext } from '../../Redirector'

const formSubmittedAction = result => dispatch => ({
  // do stuff..
  dispatch(transitionNext(`/items/${result.id}`))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment