• Stars
    star
    1,104
  • Rank 40,431 (Top 0.9 %)
  • Language
    JavaScript
  • Created over 8 years ago
  • Updated almost 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Universal data fetching and route lifecycle management for React etc.

Build Status Coverage Status npm

redial

Universal data fetching and route lifecycle management for React etc.

$ npm install --save redial

Why?

When using something like React Router, you'll want to ensure that all data for a set of routes is prefetched on the server before attempting to render.

However, as your application grows, you're likely to discover the need for more advanced route lifecycle management.

For example, you might want to separate mandatory data dependencies from those that are allowed to fail. You might want to defer certain data fetching operations to the client, particularly in the interest of server-side performance. You might also want to dispatch page load events once all data fetching has completed on the client.

In order to accommodate these scenarios, the ability to define and trigger your own custom route-level lifecycle hooks becomes incredibly important.

Providing lifecycle hooks

The @provideHooks decorator allows you to define hooks for your custom lifecycle events, returning promises if any asynchronous operations need to be performed. When using something like React Router, you'll want to decorate your route handlers rather than lower level components.

For example:

import { provideHooks } from 'redial';

import React, { Component } from 'react';
import { getSomething, getSomethingElse, trackDone } from 'actions/things';

@provideHooks({
  fetch: ({ dispatch, params: { id } }) => dispatch(getSomething(id)),
  defer: ({ dispatch, params: { id } }) => dispatch(getSomethingElse(id)),
  done: ({ dispatch }) => dispatch(trackDone())
})
class MyRouteHandler extends Component {
  render() {
    return <div>...</div>;
  }
}

If you'd prefer to avoid using decorators, you can use provideHooks as a plain old function:

const hooks = {
  fetch: ({ dispatch, params: { id } }) => dispatch(getSomething(id)),
  defer: ({ dispatch, params: { id } }) => dispatch(getSomethingElse(id)),
  done: ({ dispatch }) => dispatch(trackDone())
};

class MyRouteHandler extends Component {
  render() {
    return <div>...</div>;
  }
}

export default provideHooks(hooks)(MyRouteHandler);

Triggering lifecycle events

Once you've decorated your components, you can then use the trigger function to initiate an event for an arbitrary array of components, or even a single component if required. Since hooks tend to be asynchronous, this operation always returns a promise.

For example, when fetching data before rendering on the server:

import { trigger } from 'redial';

const locals = {
  some: 'data',
  more: 'stuff'
};

trigger('fetch', components, locals).then(render);

Dynamic locals

If you need to calculate different locals for each lifecycle hook, you can provide a function instead of an object. This function is then executed once per lifecycle hook, with a static reference to the component provided as an argument.

For example, this would allow you to calculate whether a component is being rendered for the first time and pass the result in via the locals object:

const getLocals = component => ({
  isFirstRender: prevComponents.indexOf(component) === -1
});

trigger('fetch', components, getLocals).then(render);

Example usage with React Router and Redux

When server rendering with React Router (or using the same technique to render on the client), the renderProps object provided to the match callback has an array of routes, each of which has a component attached. You're also likely to want to pass some information from the router to your lifecycle hooks.

In order to dispatch actions from within your hooks, you'll want to pass in a reference to your store's dispatch function. This works especially well with redux-thunk to ensure your async actions return promises.

Example server usage

import { trigger } from 'redial';

import React from 'react';
import { renderToString } from 'react-dom/server';
import { RouterContext, createMemoryHistory, match } from 'react-router';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';

// Your app's reducer and routes:
import reducer from './reducer';
import routes from './routes';

// Render the app server-side for a given path:
export default path => new Promise((resolve, reject) => {
  // Set up Redux (note: this API requires redux@>=3.1.0):
  const store = createStore(reducer, applyMiddleware(thunk));
  const { dispatch, getState } = store;

  // Set up history for router:
  const history = createMemoryHistory(path);

  // Match routes based on history object:
  match({ routes, history }, (error, redirectLocation, renderProps) => {
    // Get array of route handler components:
    const { components } = renderProps;

    // Define locals to be provided to all lifecycle hooks:
    const locals = {
      path: renderProps.location.pathname,
      query: renderProps.location.query,
      params: renderProps.params,

      // Allow lifecycle hooks to dispatch Redux actions:
      dispatch
    };

    // Wait for async data fetching to complete, then render:
    trigger('fetch', components, locals)
      .then(() => {
        const state = getState();
        const html = renderToString(
          <Provider store={store}>
            <RouterContext {...renderProps} />
          </Provider>
        );

        resolve({ html, state });
      })
      .catch(reject);
  });
});

Example client usage

import { trigger } from 'redial';

import React from 'react';
import { render } from 'react-dom';
import { Router, browserHistory, match } from 'react-router';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';

// Your app's reducer and routes:
import reducer from './reducer';
import routes from './routes';

// Render the app client-side to a given container element:
export default container => {
  // Your server rendered response needs to expose the state of the store, e.g.
  // <script>
  //   window.INITIAL_STATE = <%- require('serialize-javascript')(state)%>
  // </script>
  const initialState = window.INITIAL_STATE;

  // Set up Redux (note: this API requires redux@>=3.1.0):
  const store = createStore(reducer, initialState, applyMiddleware(thunk));
  const { dispatch } = store;

  // Listen for route changes on the browser history instance:
  browserHistory.listen(location => {
    // Match routes based on location object:
    match({ routes, location }, (error, redirectLocation, renderProps) => {
      // Get array of route handler components:
      const { components } = renderProps;

      // Define locals to be provided to all lifecycle hooks:
      const locals = {
        path: renderProps.location.pathname,
        query: renderProps.location.query,
        params: renderProps.params,

        // Allow lifecycle hooks to dispatch Redux actions:
        dispatch
      };

      // Don't fetch data for initial route, server has already done the work:
      if (window.INITIAL_STATE) {
        // Delete initial data so that subsequent data fetches can occur:
        delete window.INITIAL_STATE;
      } else {
        // Fetch mandatory data dependencies for 2nd route change onwards:
        trigger('fetch', components, locals);
      }

      // Fetch deferred, client-only data dependencies:
      trigger('defer', components, locals);
    });
  });

  // Render app with Redux and router context to container element:
  render((
    <Provider store={store}>
      <Router history={browserHistory} routes={routes} />
    </Provider>
  ), container);
};

Boilerplates using redial

Related projects

License

MIT License

More Repositories

1

stellar.js

Stellar.js - Parallax scrolling made easy
JavaScript
4,642
star
2

static-site-generator-webpack-plugin

Minimal, unopinionated static site generator powered by webpack
JavaScript
1,608
star
3

react-themeable

Utility for making React components easily themeable
JavaScript
550
star
4

fathom

Fathom.js - Present JavaScript in its native environment.
JavaScript
527
star
5

redux-analytics

Analytics middleware for Redux
JavaScript
489
star
6

react-to-html-webpack-plugin

Webpack plugin that renders React components to HTML files
JavaScript
166
star
7

postcss-local-scope-example

Example usage of postcss-local-scope
JavaScript
136
star
8

presentation-build-wars-gulp-vs-grunt

CSS
77
star
9

tmpload

Asynchronous Template Loading and Caching for jQuery Templates
JavaScript
62
star
10

redux-tap

Simple side-effect middleware for Redux
JavaScript
58
star
11

remix-vanilla-extract-prototype

TypeScript
53
star
12

serviceworker-loader

ServiceWorker loader for Webpack
JavaScript
52
star
13

gulp-coveralls

Gulp plugin to send code coverage to Coveralls
JavaScript
45
star
14

web-app-manifest-loader

Web app manifest loader for webpack
JavaScript
41
star
15

isolated-scroll

Prevent scoll events from bubbling up to parent elements
HTML
40
star
16

nextjs-vanilla-extract-example

TypeScript
36
star
17

grunt-micro

Ensure your micro-framework stays micro
JavaScript
35
star
18

react-isolated-scroll

React component for isolated-scroll
JavaScript
34
star
19

figma-leading-trim

Figma plugin for trimming space above and below text elements
TypeScript
29
star
20

react-static-site-playground

WIP
JavaScript
26
star
21

jquery-html5data

$.html5data
JavaScript
22
star
22

presentation-a-state-of-change-object-observe

JavaScript
22
star
23

css-modules-in-js-demo

Working demo of using JavaScript as a CSS Modules preprocessor
JavaScript
21
star
24

astro-vanilla-extract-demo

Basic demo of Astro and vanilla-extract
Astro
18
star
25

Eventralize

jQuery Events for Object Oriented JavaScript
JavaScript
18
star
26

presentation-the-case-for-css-modules

HTML
15
star
27

node-lanyrd-scraper

Lanyrd event scraper for Node.js
JavaScript
14
star
28

allthethings.js

Let your array iterations read like actual sentences
JavaScript
11
star
29

fifteen-kilos-webpack-plugin

Bring the magic of fifteen-kilos to your entire project
HTML
11
star
30

instrument-methods

Simple object method instrumentation
JavaScript
11
star
31

react-fifteen-kilos

Bring the magic of fifteen-kilos to your entire React application
JavaScript
10
star
32

react-progressive-component-starter

WIP
JavaScript
9
star
33

presentation-a-unified-styling-language

HTML
8
star
34

reconomise

Crowd sourced local business support network and priority ranking system. 'Best Use of SAPI' at RHoK Melbourne June '12.
JavaScript
8
star
35

react-themeable-experiment

WIP
JavaScript
7
star
36

bespoke-remote-prototype

Prototype presentation for bespoke-remote
JavaScript
7
star
37

presentation-the-end-of-global-css

HTML
6
star
38

angular-delegator

Write smaller, cleaner AngularJS services
JavaScript
6
star
39

presentation-bespoke.js

DIY Presentations with Bespoke.js
JavaScript
5
star
40

batsignal

Help radiator for remote agile teams. Built using Meteor.
JavaScript
5
star
41

presentation-return-of-the-progressive-web

The Return of the Progressive Web
HTML
5
star
42

redux-hotjar

Declarative Hotjar tagging for Redux
JavaScript
4
star
43

stellar.js-site

Stellar.js Project Page
JavaScript
4
star
44

webpack-serviceworker-demo

Webpack Service Worker demo
JavaScript
4
star
45

presentation-first-class-styles

HTML
4
star
46

indiana

Experimental isomorphic JavaScript demo
JavaScript
3
star
47

bespoke-webpack-boilerplate

Bespoke.js boilerplate powered by Webpack
JavaScript
3
star
48

markdalgleish.com

My personal blog - built with Octopress
JavaScript
3
star
49

remix-vite-css-url-demo

Demo of Remix + Vite + .css?url
JavaScript
3
star
50

stateless-dtm

Purely stateless interface for Dynamic Tag Manager
JavaScript
3
star
51

twitface

Twitter avatar API client for Node.js
JavaScript
2
star
52

chook-jstestdriver

JsTestDriver adapter for Chook, the headless, framework-agnostic unit test runner for Node.js
JavaScript
2
star
53

chook

Headless, framework-agnostic unit test runner for Node.js
JavaScript
2
star
54

css-hooks-playground

Just playing around with CSS Hooks
TypeScript
2
star
55

remix-vite-cloudflare-workers-playground

Demo app using Remix with Vite on Cloudflare Workers
TypeScript
1
star
56

postcss-local-scope-inheritance-example

Example usage of postcss-local-scope with class inheritance
JavaScript
1
star
57

redux-helloworld

Just playing around with Redux
JavaScript
1
star
58

zenhub

Placeholder repo for my Zenhub mega-board
1
star
59

css-modules-selector-experiment

Exploration of non-class selectors in CSS Modules
JavaScript
1
star
60

cuecard

iPad-controlled presentation framework for Node.js
JavaScript
1
star
61

tmpload-site

tmpload Project Page
JavaScript
1
star
62

Eventralize-site

Eventralize Project Page
JavaScript
1
star
63

presentation-dawn-of-the-progressive-single-page-app

HTML
1
star
64

fathom-site

Fathom.js Project Page
JavaScript
1
star
65

cuecard-example

Example usage of Cuecard
JavaScript
1
star
66

kansas

Experimental stereoscopic rendering for React components
JavaScript
1
star
67

ducks-component-experiment

Experimental React component powered by Ducks
JavaScript
1
star
68

bespoke.js-site

Bespoke.js Project Page
CSS
1
star
69

preconstruct-node-esm-import-issue

JavaScript
1
star
70

presentation-a-bespoke-ecosystem

JavaScript
1
star
71

presentation-tabs

Ryan loses
CSS
1
star
72

baltic

Experimental continuous deployment with Codeship for Bespoke.js
JavaScript
1
star
73

presentation-web-components

Web Components: Why You're Already An Expert
JavaScript
1
star
74

bespoke-theme-prototype

CSS
1
star
75

angular-lisa-example

Sample app wiring AngularJS and Lisa together
JavaScript
1
star
76

balance-parens

Balance a string of parentheses.
JavaScript
1
star
77

chook-zombie

Experimental Zombie support for Chook
JavaScript
1
star
78

jquery-html5data-site

$.html5data Project Page
JavaScript
1
star
79

walletconnnect-deeplink-prompt-issue

TypeScript
1
star
80

melbcss-modules-hello-world

A simple CSS Modules example, extracted from a live coding demo at MelbCSS
JavaScript
1
star