Is it possible to call an async redux action known as a thunk
on a particular route and not perform the transition until the response has succeeded or failed?
Use Case
We need to load data from the server and fill a form with initial values. These initial values don't exist until the data is fetched from the server.
some syntax like this would be great:
<Route path="/myForm" component={App} async={dispatch(loadInitialFormValues(formId))}>
To answer the original question of preventing the transition to a new route until a response has succeeded or failed:
Because you're using redux thunk you could have the success or failure in the action creator trigger the redirect. I don't know what your specific action / action creator looks like but something like this could work:
Follow up. Common pattern of loading data on entering a route / on componentWillMount of a component and displaying a spinner:
From the redux docs on async actions http://redux.js.org/docs/advanced/AsyncActions.html
I followed this general pattern below using your situation as a rough guideline. You do not have to use promises
First and foremost, I want to say that there is a debate around the topic of fetching data with react-router's
onEnter
hooks whether or not is good practice, nevertheless this is how something like that would go:You can pass the redux-store to your
Router
. Let the following be your Root component, whereRouter
is mounted:And your routes will be something like:
Please notice that your router file is exporting a thunk with your store as argument, if you look upwards, see how we invoked the router, we pass the store object to it.
Sadly, at the time of writing react-router docs return 404 to me, thus I cannot point you to the docs where
(nextState, transition, callback)
are described. But, about those, from my memory:nextState
describes the routereact-router
will transition to;transition
function to preform maybe another transition than the one fromnextState
;callback
will trigger your route transition to finish.Another think to point out is that with redux-thunk, your dispatch action can return a promise, check it in the docs here. You can find here a good example on how to configure your redux store with redux-thunk.
now
browserHistory
is not work due to this error:use this code instead:
and use
on your
fetch
or any where else.