markdalgleish/redial

Doc improvement for client-only?

quicksnap opened this issue · 1 comments

I love the concept of redial and gave it a whirl with react-router. However, I'm not using server rendering.

I went through some loops to get it working the way I prefer. My use case is that I want a callback ('fetch') to fire whenever a route is visited or "refreshed" by clicking the link for the current route.

In your examples, this is accomplished by using history.listen(). The issue with this approach is that it will not fire on the initial page load. Also, using match on the client causes onEnter callbacks to fire multiple times, which is not good.

My solution was to do something like this:

const triggerRedial = (nextState, replace) => {
  const locals = {
    path: nextState.location.pathname,
    query: nextState.location.query,
    params: nextState.params,
    dispatch: dispatch, // Accessed vial closure
  };

  const components = nextState.routes.map(c => c.component);
  trigger('fetch', components, locals);
};

// ..snip..

<Route
  path='/'
  component={Root}
  onEnter={triggerRedial}
  onChange={(prev, ...rest) => triggerRedial(...rest)}
>
  {/* All children routes */}
</Route>

onEnter does what you would expect, and onChange handles the case of when the existing route changes within itself. This doesn't cause duplicate firings, and seems to work great.

Should we consider updating the docs with this example?

Another option is creating a react-router middleware:

const redialMiddleware = {
  renderRouterContext: (child, props) => {
    trigger('fetch', props.components, getTriggerLocals(props, dispatch));
    return child;
  },
};

<Router render={applyRouterMiddleware(redialMiddleware, /* others */)}>