After reading many questions regarding this topic I am still unsure as to which is the best way to asynchronously fetch data which later will be passed down as props to the child routes with React Router v1.0.0 and up.
My route config looks something like this:
import { render } from 'react-dom';
// more imports ...
...
render(
<Router>
<Route path="/" component={App} />
<IndexRoute component={Dashboard}/>
<Route path="userpanel" component={UserPanel}/>
</Router>,
document.getElementById('container')
)
In my App
component I have code which asynchronously fetches data from the backend and will incorporate it into its state, if fetching was successful. I use componentDidMount
for this within App
.
The state of App will look like this contrived example:
{
user: {
name: 'Mike Smith',
email: 'mike@smith.com'
}
}
I would want to pass the user
part of state as props to my IndexRoute
and the userpanel
route. However I am not sure how I should do this.
A few questions come to mind:
- Should I place the async data request somewhere else within my code?
- Should I use the React Router api (like
onEnter
) instead of React lifecycle methods for the data fetching? - How can I pass the state (user) of
App
to theDashboard
andUserPanel
components as props? - I am unsure how to do this with
React.cloneElement
as seen in other answers.
Thanks for the help in advance.