kriasoft / universal-router

A simple middleware-style router for isomorphic JavaScript web apps
https://www.kriasoft.com/universal-router/
MIT License
1.7k stars 104 forks source link

Relay Modern #134

Open alexhawkins opened 6 years ago

alexhawkins commented 6 years ago

Does this router work well with Relay Modern? Specifically, does it avoid request waterfalls from nesting QueryRenderer components? The Relay team recommends using Found for this specific reason as you can see here https://facebook.github.io/relay/docs/routing.html#custom-routing-and-more However, I'm interested in using your react starter kit and would be curious if universal router would be suitable to use with Relay Modern.

koistya commented 6 years ago

I'm using it successfully with Relay Modern without any issues. A simplified example looks like this:

import UniversalRouter from 'universal-router';
import { graphql } from 'relay-runtime';

const routes = [
  { path: '', query: graphql`...`, render: ({ data }) => ... },
  { path: '/posts', query: graphql`...`, render: ({ data }) => ... },
  { path: '/posts/:id', query: graphql`...`, render: ({ data }) => ... },
];

async function resolveRoute(context, params) {
  const data = await context.fetch(context.route.query, params);
  return context.route.render({ ...context, data });
}

const router = new UniversalRouter(routes, { resolveRoute });

The top-level React component must render Relay's <QueryRenderer> and subscribe to changes in URL:

componentDidMount() {
  history.listen(this.onLocationChange);
}
onLocationChange = location => {
  router.resolve({
    ...location,
    fetch: (query, variables) => ... , // pass to <QueryRenderer>
  }).then(...);
};
render() {
  return <QueryRenderer ... />;
}

It works well with both SPA and server-side rendered apps with a few tweaks.

Also see kriasoft/react-static-boilerpalte - using Creact React App + Universal Router + Relay Modern