You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
First of all, I love this library and the patterns you guys are using. 👍👍
I'm trying to use redux to build an isomorphic app. It's working beautifully so far, except that I need to figure out how to wait until my stores have loaded (on the server) before returning the initial page load. Ideally, the loading should take place in the stores themselves, but when I call dispatch(userActions.load()), the store has to return the new state (i.e. return { ...state, loading: true };), so it can't return a promise to wait for. dispatch() returns the action passed to it for some reason. I'd really like something like...
Ideally, the loading should take place in the stores themselves
Redux enforces that Stores are completely synchronous. What you describe should happen in the action creator instead.
I think it may even be possible with the default thunk middleware. Your action creator would look like:
exportfunctiondoSomethingAsync(){return(dispatch)=>{dispatch({type: SOMETHING_STARTED});returnrequestSomething().then((result)=>dispatch({type: SOMETHING_COMPLETED, result }),(error)=>dispatch({type: SOMETHING_FAILED, error }));};}
and handling the actual (granular) actions in the Store.
It's also possible to write a custom middleware to remove the boilerplate.
Reacted by David Jones, Abel Chalier, Rodrigo Formigone, Lucas Paulger, Guilherme Kodama, Tomasz Cichocinski, BT Burton, George Lifchits, Wilfred Hughes, Zetta Flow and 17 more
Reacted by Sanket Sahu, anothermohit, kiran ps, Solomon Ayoola, Jordi Dosne, Mark Murray, Pavel Makeenko, Efroim Rosenberg, 马超, Anil Gupta and 16 more
Reacted by Ivan Montiel, Vadim Gribanov, Anibal, Nithin Peter, Isman Usoh, Bojan Dragojevic, Solomon Ayoola, Minjun Kim, Francisco, Efroim Rosenberg and 4 more
Ooh, that's nice as well, and more of what I had in mind when I asked the original question. I can't tell if I like the tradeoff in reducing the number of action constants in exchange for adding ifs to check the readyState inside the store. I think I might prefer having addtional _SUCCESS and _FAILURE versions of each action just to avoid putting an if inside a case.
Yeah that's totally up to your taste. You could have a similar version that turns types: { request: ..., success: ..., failure: ... } into actions. This is the point of making it a middleware instead of baking into the library: everybody has their own taste to these things.
Oh man, I love that solution. So much nicer than having the then() and additional calls to dispatch() like the first solution you proposed. Hooray for middleware!
This is just pseudocode, so don't go pasting this anywhere, but I'm using react-router (whose api is changing as fast as redux's) something like this:
app.get('/my-app',(req,res)=>{Router.run(routes,req.path,(error,initialState)=>{Promise.all(initialState.components.filter(component=>component.fetchData)// only components with a static fetchData().map(component=>{// have each component dispatch load actions that return promisesreturncomponent.fetchData(redux.dispatch);}))// Promise.all combines all the promises into one.then(()=>{// now fetchData() has been run on every component in my route, and the// promises resolved, so we know the redux state is populatedres.send(generatePage(redux));});});});
@erikras Regarding your last comment where you are calling the fetchData method on what you have as initialState.components (in the callback of Router.run), the object you get the component references from only return the route handlers matched. What are your thoughts on reaching components that might not be a matched route handler, i.e a child component, but needs to fetch data?
here's an example of what I'm talking about
importReactfrom'react';importRouterfrom'react-router';import{Route,RouteHandler,DefaultRoute}from'react-router';//imagine Bar needs some dataconstBar=React.createClass({render(){return(<div>bar</div>);}});constFoo=React.createClass({render(){return(<div>
foo
<Bar/></div>);}});constApp=React.createClass({render(){return(<div><RouteHandler/></div>);}});constroutes=(<Routepath="/"handler={App}name="App"><DefaultRoutehandler={Foo}name="Foo"/></Route>);Router.run(routes,'/',function(Root,state){console.log(state);});
I get around this by preventing the fetch code from executing if the store is already full
Okey, I got that. Thanks.
However, the solution posed above requires each page to know the data for all of its children components.
Maybe I misread your solution, but isn't this a necessary requirement regardless of the server-side rendering? (e.g. it should render the same state, if I refresh on the current route, even if it is a SPA)
@chemoish I'm not sure if we are on the same page. Let me try to explain what my point of view is.
For example I got three nested components:
component1 (static dataFetch1)
component2 (static dataFetch2)
component3 (static dataFetch3)
Each of them have there own "componentDidMount" methods, with there own dataFetching declarations (dispatching actions via its static dataFetching method).
If I do not have sever-side rendering and I refresh the current URL, my components will mount and trigger all the actions needed to load all the required data afterwards.
With server-side rendering, your match function and renderProps will extract all three components, so I can access all of the static dataFetching methods, which will then allow me to fetch all the data needed for the initial server-side rendering?
Do you have a reference to your match function from your provided example? Thx.
@ms88privatrenderProps.components is an array of router components, it doesn't go deeper than that. @chemoish meant that with his implementation you cannot describe the data fetching needs on deeper components.
Yes, I have looked through it. But I didn't get, how to make sure data
fetching hooked will not run second time after reinitialization code to n
client.
On Пт, 18 марта 2016 г. at 22:54, Sean Matheson notifications@github.com
wrote:
Also curious if anyone has found a stable solution for this challenge. I love @erikras's boilerplate, but as @vtambourine mentioned, it has moved to redux-async-connect which seems like it may not be a stable long-term solution: #81 Is redux-async-connect dead?.
for those interested in a redux solution with middleware as mentioned by @gaearon I have an example project which implements this technique and allows the components themselves request the data they need server-side
Activity
gaearon commentedon Jun 15, 2015
Hey, thanks!
Redux enforces that Stores are completely synchronous. What you describe should happen in the action creator instead.
I think it may even be possible with the default thunk middleware. Your action creator would look like:
and handling the actual (granular) actions in the Store.
It's also possible to write a custom middleware to remove the boilerplate.
erikras commentedon Jun 15, 2015
Genius! I figured I was overlooking something obvious. I like that separation of doing and storing.
I look forward to watching this library grow, although it's pretty doggone complete already. Cheers, @gaearon!
gaearon commentedon Jun 15, 2015
You can also write a custom middleware like this
and use it instead of the default one.
This will let you write async action creators like
and have them turn into
erikras commentedon Jun 15, 2015
Ooh, that's nice as well, and more of what I had in mind when I asked the original question. I can't tell if I like the tradeoff in reducing the number of action constants in exchange for adding
ifs to check thereadyStateinside the store. I think I might prefer having addtional_SUCCESSand_FAILUREversions of each action just to avoid putting anifinside acase.Thanks, though.
gaearon commentedon Jun 15, 2015
Yeah that's totally up to your taste. You could have a similar version that turns
types: { request: ..., success: ..., failure: ... }into actions. This is the point of making it a middleware instead of baking into the library: everybody has their own taste to these things.gaearon commentedon Jun 15, 2015
erikras commentedon Jun 15, 2015
Oh man, I love that solution. So much nicer than having the
then()and additional calls todispatch()like the first solution you proposed. Hooray for middleware!gaearon commentedon Jun 15, 2015
Let me know how (and whether ;-) it works!
We have not really tested custom middleware much.
erikras commentedon Jun 15, 2015
You left out a
}(that's -1 point 😀), but it worked like a charm! First time.gaearon commentedon Jun 15, 2015
👍
iest commentedon Jun 17, 2015
@erikras I'm curios how you implemented waiting for the promises to resolve on the server?
erikras commentedon Jun 17, 2015
This is just pseudocode, so don't go pasting this anywhere, but I'm using react-router (whose api is changing as fast as redux's) something like this:
Does that clear anything up?
gaearon commentedon Jun 17, 2015
@iest
Quoting your problem in Slack:
I think the problem here is you're not actually returning anything from
fooBar's nested method.Either remove the braces:
or add an explicit
returnstatement:Either way, it might be easier to use a custom promise middleware as suggested above.
mattybow commentedon Jun 17, 2015
@erikras Regarding your last comment where you are calling the fetchData method on what you have as
initialState.components(in the callback of Router.run), the object you get the component references from only return the route handlers matched. What are your thoughts on reaching components that might not be a matched route handler, i.e a child component, but needs to fetch data?here's an example of what I'm talking about
output:
You won't have access to Bar in Routes
37 remaining items
ms88privat commentedon Feb 17, 2016
@chemoish
Okey, I got that. Thanks.
Maybe I misread your solution, but isn't this a necessary requirement regardless of the server-side rendering? (e.g. it should render the same state, if I refresh on the current route, even if it is a SPA)
chemoish commentedon Feb 17, 2016
It would, but you may want a nested component manage its own data fetching, for whatever reason.
For instance, a component that is repeated on many pages, but each page doesn't have much data fetching needs.
ms88privat commentedon Feb 17, 2016
@chemoish I'm not sure if we are on the same page. Let me try to explain what my point of view is.
For example I got three nested components:
Each of them have there own "componentDidMount" methods, with there own dataFetching declarations (dispatching actions via its static dataFetching method).
If I do not have sever-side rendering and I refresh the current URL, my components will mount and trigger all the actions needed to load all the required data afterwards.
With server-side rendering, your
matchfunction andrenderPropswill extract all three components, so I can access all of the static dataFetching methods, which will then allow me to fetch all the data needed for the initial server-side rendering?Do you have a reference to your
match functionfrom your provided example? Thx.dominictobias commentedon Feb 17, 2016
@ms88privat
renderProps.componentsis an array of router components, it doesn't go deeper than that. @chemoish meant that with his implementation you cannot describe the data fetching needs on deeper components.ms88privat commentedon Feb 17, 2016
@dominictobias thx, do you have a solution to this problem? Is there a possibility to get all the nested components?
sompylasar commentedon Feb 17, 2016
Probably this can help? https://github.com/gaearon/react-side-effect
Used to collect all meta tags from nested elements: https://github.com/nfl/react-helmet
vtambourine commentedon Mar 11, 2016
Sorry for bumping this discussion again, but I have recently run into the same problem of prefilling state with async action.
I can see that @erikras moved his boilerplate project to redux-async-connect. I wonder, if somebody found another solution?
ctrlplusb commentedon Mar 18, 2016
@vtambourine I have been looking at https://github.com/markdalgleish/redial which is quite helpful
vtambourine commentedon Mar 18, 2016
Yes, I have looked through it. But I didn't get, how to make sure data
fetching hooked will not run second time after reinitialization code to n
client.
On Пт, 18 марта 2016 г. at 22:54, Sean Matheson notifications@github.com
wrote:
isTravis commentedon May 12, 2016
Also curious if anyone has found a stable solution for this challenge. I love @erikras's boilerplate, but as @vtambourine mentioned, it has moved to redux-async-connect which seems like it may not be a stable long-term solution: #81 Is redux-async-connect dead?.
AVVS commentedon May 24, 2016
@vtambourine there is a fork thats available at https://github.com/makeomatic/redux-connect and is well-maintained. It has similar API with a few changes to it, check it out if you are interested
peter-mouland commentedon Sep 3, 2016
for those interested in a redux solution with middleware as mentioned by @gaearon I have an example project which implements this technique and allows the components themselves request the data they need server-side
https://github.com/peter-mouland/react-lego-2016#redux-with-promise-middleware
serraventura commentedon Oct 18, 2016
How to unit test action creator with this approach?