javascript - How to make API calls with server side rendering in React -
i have server side rendering , running having trouble figuring out how include data external api in renders. here core files.
server.js
import express 'express' import react 'react' import { rendertostring } 'react-dom/server' import { staticrouter } 'react-router-dom' import template './template' // html template import app './client' const server = express() server.get('*', (req, res) => { const context = {} const appstring = rendertostring( <staticrouter location={req.url} context={context}> <app/> </staticrouter> ); res.send(template({ body: appstring, title: 'ssr', })); }); const port = 8080; server.listen(port); console.log(listening on port ${port})
client.js
import react 'react'; import { render } 'react-dom' import { router, browserrouter, route, switch } 'react-router-dom' import home './containers/home' const app = () => ( <switch> <route path='/' exact component={home} /> </switch> ) if (typeof window !== 'undefined') { render( <browserrouter><app /></browserrouter>, document.getelementbyid('root') ) } export default app
home.js
import react 'react' import layout './layout' import someaction '../actions/someaction' // action calls external api export default class home extends react.component { constructor(props) { super(props) this.state = { data: null } } // somehow use "someaction" hydrate this.state.data render // can return data external api render() { return ( <layout> {this.state.data} </layout> ) } } }
the code meant simple outline of how got server side rendering working react. question how use action calls external api , include returned data in component render()
. i'm thinking way server.js
rendertostring()
complete html.
Comments
Post a Comment