react-ssr-setup icon indicating copy to clipboard operation
react-ssr-setup copied to clipboard

Async fetch on server side for a route

Open tpriyesh opened this issue 3 years ago • 1 comments

How to handle async fetch for a route on server side? I have gone through the codebase but haven't seen anything to do that. Currently I see only static server side data support. Am I missing anything or Do we need to write our own middleware which will match route and call some method (like loadData) which dispatch some action and populate the reducer

tpriyesh avatar Sep 01 '20 07:09 tpriyesh

Since no one has replied even though it's 3.5 months later. You have to use an isomorphic fetch library first of all. Second of all you want to write a file called routes.js and iterate over it's routes for both in your client entry point and your server entry point.

// routes.js
import fetch from 'isomorphic-fetch'
import AppContainer from './containers/appContainer'
import putDataInReducers from './myHelperFile'

export default [
  {
    path: '/post/:id',
    loadData: async function(req) {
      const { data } = await fetch(`${process.env.API_ENDPOINT}/api/v1/post/${req.params.id}`)
      putDataInReducers(data)
    },
    container: AppContainer,
    ...
  },
  ...
]
// server entry point
import routes from './routes'

const router = MyRouterOfChoice()

routes.map(route => router.get(route.path, (req, res) => route.loadData(req))

app.use(router)
// client entry point
import routes from './routes'

const MyAppEntryPoint = () => (
  <BrowserRouter>
    {routes.map(r => <Route path={r.path} component={r.container} />)}
  </BrowserRouter>
)

That's basically how it's done in a nutshell, there's a lot of questions that I'm not answering here but that's the basis, if you understand ReactDOM.hydrate and Express and React-router you should be OK to go from here. I found this documentation very useful: https://reactrouter.com/web/guides/server-rendering

LouisRitchie avatar Dec 16 '20 06:12 LouisRitchie