SimpleContacts / react-router-async-routes

React Router 4 with Server Side Rendering and Async Routes
9 stars 1 forks source link

Redux Connect #1

Open nicolashemonic opened 7 years ago

nicolashemonic commented 7 years ago

Hi, Can i connect a component to Redux with async rendering ? Something like this would be great :

{/* Fetch data before render */} <Route async path="/page3" render={({ store: { dispatch } }) => dispatch(fetchSomething())} />

Or any pattern suggestion is welcome :) Thanks !

sfarthin commented 6 years ago

Sorry for the extremely late response. This is one way:

// routes.js
const routes = ({ store }) => {
  return (
    <Switch>
      <Route
          async
          exact
          path="/test"
          component={() => store.dispatch("SOME_ACTION")
      />
    </Switch>
  )
});

// client.js
import routes from './routes.js'
import { ResolveRoutes } from '@simple-contacts/react-router-async-routes';

async function render() {
  // Lets make sure our current route can be rendered sync.
  const markup = await ResolveRoutes(
    routes({ store }),
    window.location.pathname,
  );

  React.render(markup, document.getElementById('root'));
}

// server.js
import routes from './routes.js'
import { ResolveRoutes } from '@simple-contacts/react-router-async-routes';

app.get('*', async (req, res, next) => {
  const markup = await ResolveRoutes(
    routes({ store }),
    req.pathname,
  );

  res.write(React.renderToString(markup));
});