I am building a React web-app with the data for the component stored in a mongoDB instance. As I understand I need to retrieve all of the data before I render out the component. I am not sure how to do it when mongoose returns promises and data flows asynchronously. How should I pass the data to the component?
//routing.jsx
mongoose.connect(isProd ? 'mongodb://localhost:27017/real' : 'mongodb://localhost:27017/test')
function getCourses() {
return Course
.find({})
.then(docs => docs)
.catch(err => console.log(err))
}
function loadHomeData() {
const promises = []
promises.push(getCourses())
Promise.all(promises).then((data) => {
return data
}).catch(err => console.log(err))
}
function loadCoursesData() {
}
const ROUTES = [
{ route: '/', label: 'Home', component: <HomePage />, loadData: loadHomeData },
{ route: '/courses', label: 'Courses', component: <CoursesPage />, loadData: loadCoursesData },
]
export default ROUTES
//routing.js
export default (app: Object) => {
ROUTES.map(route =>
app.get(route.route, (req, res) => {
res.send(renderApp(req.url,route.loadData()))
})
)
}
//render-app.jsx
const renderApp = (location: string, data: Object) => {
const head = Helmet.rewind()
const appHtml = ReactDOMServer.renderToString(
<StaticRouter location={location} context={data}>
<App />
</StaticRouter>
)
via Sultan Kenjeyev
No comments:
Post a Comment