Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Async fetch on server side for a route #133

Open
tpriyesh opened this issue Sep 1, 2020 · 1 comment
Open

Async fetch on server side for a route #133

tpriyesh opened this issue Sep 1, 2020 · 1 comment

Comments

@tpriyesh
Copy link

tpriyesh commented Sep 1, 2020

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

@LouisRitchie
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants